]> git.lizzy.rs Git - rust.git/blob - crates/hir_expand/src/db.rs
Merge #11115
[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             // FIXME: Note how we convert from `Parse` to `SyntaxNode` here,
219             // forgetting about parse errors.
220             db.parse_macro_expansion(macro_file).value.map(|(it, _)| it.syntax_node())
221         }
222     }
223 }
224
225 fn parse_macro_expansion(
226     db: &dyn AstDatabase,
227     macro_file: MacroFile,
228 ) -> ExpandResult<Option<(Parse<SyntaxNode>, Arc<mbe::TokenMap>)>> {
229     let _p = profile::span("parse_macro_expansion");
230     let result = db.macro_expand(macro_file.macro_call_id);
231
232     if let Some(err) = &result.err {
233         // Note:
234         // The final goal we would like to make all parse_macro success,
235         // such that the following log will not call anyway.
236         let loc: MacroCallLoc = db.lookup_intern_macro_call(macro_file.macro_call_id);
237         let node = loc.kind.to_node(db);
238
239         // collect parent information for warning log
240         let parents =
241             std::iter::successors(loc.kind.file_id().call_node(db), |it| it.file_id.call_node(db))
242                 .map(|n| format!("{:#}", n.value))
243                 .collect::<Vec<_>>()
244                 .join("\n");
245
246         tracing::warn!(
247             "fail on macro_parse: (reason: {:?} macro_call: {:#}) parents: {}",
248             err,
249             node.value,
250             parents
251         );
252     }
253     let tt = match result.value {
254         Some(tt) => tt,
255         None => return ExpandResult { value: None, err: result.err },
256     };
257
258     let expand_to = macro_expand_to(db, macro_file.macro_call_id);
259
260     tracing::debug!("expanded = {}", tt.as_debug_string());
261     tracing::debug!("kind = {:?}", expand_to);
262
263     let (parse, rev_token_map) = match token_tree_to_syntax_node(&tt, expand_to) {
264         Ok(it) => it,
265         Err(err) => {
266             tracing::debug!(
267                 "failed to parse expansion to {:?} = {}",
268                 expand_to,
269                 tt.as_debug_string()
270             );
271             return ExpandResult::only_err(err);
272         }
273     };
274
275     match result.err {
276         Some(err) => {
277             // Safety check for recursive identity macro.
278             let node = parse.syntax_node();
279             let file: HirFileId = macro_file.into();
280             let call_node = match file.call_node(db) {
281                 Some(it) => it,
282                 None => {
283                     return ExpandResult::only_err(err);
284                 }
285             };
286             if is_self_replicating(&node, &call_node.value) {
287                 ExpandResult::only_err(err)
288             } else {
289                 ExpandResult { value: Some((parse, Arc::new(rev_token_map))), err: Some(err) }
290             }
291         }
292         None => {
293             tracing::debug!("parse = {:?}", parse.syntax_node().kind());
294             ExpandResult { value: Some((parse, Arc::new(rev_token_map))), err: None }
295         }
296     }
297 }
298
299 fn macro_arg(db: &dyn AstDatabase, id: MacroCallId) -> Option<Arc<(tt::Subtree, mbe::TokenMap)>> {
300     let arg = db.macro_arg_text(id)?;
301     let loc = db.lookup_intern_macro_call(id);
302
303     let node = SyntaxNode::new_root(arg);
304     let censor = censor_for_macro_input(&loc, &node);
305     let (mut tt, tmap) = mbe::syntax_node_to_token_tree_censored(&node, &censor);
306
307     if loc.def.is_proc_macro() {
308         // proc macros expect their inputs without parentheses, MBEs expect it with them included
309         tt.delimiter = None;
310     }
311
312     Some(Arc::new((tt, tmap)))
313 }
314
315 fn censor_for_macro_input(loc: &MacroCallLoc, node: &SyntaxNode) -> FxHashSet<SyntaxNode> {
316     (|| {
317         let censor = match loc.kind {
318             MacroCallKind::FnLike { .. } => return None,
319             MacroCallKind::Derive { derive_attr_index, .. } => {
320                 cov_mark::hit!(derive_censoring);
321                 ast::Item::cast(node.clone())?
322                     .attrs()
323                     .take(derive_attr_index as usize + 1)
324                     .filter(|attr| attr.simple_name().as_deref() == Some("derive"))
325                     .map(|it| it.syntax().clone())
326                     .collect()
327             }
328             MacroCallKind::Attr { invoc_attr_index, .. } => {
329                 cov_mark::hit!(attribute_macro_attr_censoring);
330                 ast::Item::cast(node.clone())?
331                     .attrs()
332                     .nth(invoc_attr_index as usize)
333                     .map(|attr| attr.syntax().clone())
334                     .into_iter()
335                     .collect()
336             }
337         };
338         Some(censor)
339     })()
340     .unwrap_or_default()
341 }
342
343 fn macro_arg_text(db: &dyn AstDatabase, id: MacroCallId) -> Option<GreenNode> {
344     let loc = db.lookup_intern_macro_call(id);
345     let arg = loc.kind.arg(db)?;
346     if matches!(loc.kind, MacroCallKind::FnLike { .. }) {
347         let first = arg.first_child_or_token().map_or(T![.], |it| it.kind());
348         let last = arg.last_child_or_token().map_or(T![.], |it| it.kind());
349         let well_formed_tt =
350             matches!((first, last), (T!['('], T![')']) | (T!['['], T![']']) | (T!['{'], T!['}']));
351         if !well_formed_tt {
352             // Don't expand malformed (unbalanced) macro invocations. This is
353             // less than ideal, but trying to expand unbalanced  macro calls
354             // sometimes produces pathological, deeply nested code which breaks
355             // all kinds of things.
356             //
357             // Some day, we'll have explicit recursion counters for all
358             // recursive things, at which point this code might be removed.
359             cov_mark::hit!(issue9358_bad_macro_stack_overflow);
360             return None;
361         }
362     }
363     Some(arg.green().into())
364 }
365
366 fn macro_def(db: &dyn AstDatabase, id: MacroDefId) -> Result<Arc<TokenExpander>, mbe::ParseError> {
367     match id.kind {
368         MacroDefKind::Declarative(ast_id) => {
369             let (mac, def_site_token_map) = match ast_id.to_node(db) {
370                 ast::Macro::MacroRules(macro_rules) => {
371                     let arg = macro_rules
372                         .token_tree()
373                         .ok_or_else(|| mbe::ParseError::Expected("expected a token tree".into()))?;
374                     let (tt, def_site_token_map) = mbe::syntax_node_to_token_tree(arg.syntax());
375                     let mac = mbe::DeclarativeMacro::parse_macro_rules(&tt)?;
376                     (mac, def_site_token_map)
377                 }
378                 ast::Macro::MacroDef(macro_def) => {
379                     let arg = macro_def
380                         .body()
381                         .ok_or_else(|| mbe::ParseError::Expected("expected a token tree".into()))?;
382                     let (tt, def_site_token_map) = mbe::syntax_node_to_token_tree(arg.syntax());
383                     let mac = mbe::DeclarativeMacro::parse_macro2(&tt)?;
384                     (mac, def_site_token_map)
385                 }
386             };
387             Ok(Arc::new(TokenExpander::DeclarativeMacro { mac, def_site_token_map }))
388         }
389         MacroDefKind::BuiltIn(expander, _) => Ok(Arc::new(TokenExpander::Builtin(expander))),
390         MacroDefKind::BuiltInAttr(expander, _) => {
391             Ok(Arc::new(TokenExpander::BuiltinAttr(expander)))
392         }
393         MacroDefKind::BuiltInDerive(expander, _) => {
394             Ok(Arc::new(TokenExpander::BuiltinDerive(expander)))
395         }
396         MacroDefKind::BuiltInEager(..) => {
397             // FIXME: Return a random error here just to make the types align.
398             // This obviously should do something real instead.
399             Err(mbe::ParseError::UnexpectedToken("unexpected eager macro".to_string()))
400         }
401         MacroDefKind::ProcMacro(expander, ..) => Ok(Arc::new(TokenExpander::ProcMacro(expander))),
402     }
403 }
404
405 fn macro_expand(db: &dyn AstDatabase, id: MacroCallId) -> ExpandResult<Option<Arc<tt::Subtree>>> {
406     let _p = profile::span("macro_expand");
407     let loc: MacroCallLoc = db.lookup_intern_macro_call(id);
408     if let Some(eager) = &loc.eager {
409         return ExpandResult {
410             value: Some(eager.arg_or_expansion.clone()),
411             // FIXME: There could be errors here!
412             err: None,
413         };
414     }
415
416     let macro_arg = match db.macro_arg(id) {
417         Some(it) => it,
418         None => return ExpandResult::str_err("Failed to lower macro args to token tree".into()),
419     };
420
421     let expander = match db.macro_def(loc.def) {
422         Ok(it) => it,
423         // FIXME: This is weird -- we effectively report macro *definition*
424         // errors lazily, when we try to expand the macro. Instead, they should
425         // be reported at the definition site (when we construct a def map).
426         Err(err) => return ExpandResult::str_err(format!("invalid macro definition: {}", err)),
427     };
428     let ExpandResult { value: tt, err } = expander.expand(db, id, &macro_arg.0);
429     // Set a hard limit for the expanded tt
430     let count = tt.count();
431     // XXX: Make ExpandResult a real error and use .map_err instead?
432     if TOKEN_LIMIT.check(count).is_err() {
433         return ExpandResult::str_err(format!(
434             "macro invocation exceeds token limit: produced {} tokens, limit is {}",
435             count,
436             TOKEN_LIMIT.inner(),
437         ));
438     }
439
440     ExpandResult { value: Some(Arc::new(tt)), err }
441 }
442
443 fn macro_expand_error(db: &dyn AstDatabase, macro_call: MacroCallId) -> Option<ExpandError> {
444     db.macro_expand(macro_call).err
445 }
446
447 fn expand_proc_macro(db: &dyn AstDatabase, id: MacroCallId) -> ExpandResult<tt::Subtree> {
448     let loc: MacroCallLoc = db.lookup_intern_macro_call(id);
449     let macro_arg = match db.macro_arg(id) {
450         Some(it) => it,
451         None => return ExpandResult::str_err("No arguments for proc-macro".to_string()),
452     };
453
454     let expander = match loc.def.kind {
455         MacroDefKind::ProcMacro(expander, ..) => expander,
456         _ => unreachable!(),
457     };
458
459     let attr_arg = match &loc.kind {
460         MacroCallKind::Attr { attr_args, .. } => {
461             let mut attr_args = attr_args.0.clone();
462             mbe::Shift::new(&macro_arg.0).shift_all(&mut attr_args);
463             Some(attr_args)
464         }
465         _ => None,
466     };
467
468     expander.expand(db, loc.krate, &macro_arg.0, attr_arg.as_ref())
469 }
470
471 fn is_self_replicating(from: &SyntaxNode, to: &SyntaxNode) -> bool {
472     if diff(from, to).is_empty() {
473         return true;
474     }
475     if let Some(stmts) = ast::MacroStmts::cast(from.clone()) {
476         if stmts.statements().any(|stmt| diff(stmt.syntax(), to).is_empty()) {
477             return true;
478         }
479         if let Some(expr) = stmts.expr() {
480             if diff(expr.syntax(), to).is_empty() {
481                 return true;
482             }
483         }
484     }
485     false
486 }
487
488 fn hygiene_frame(db: &dyn AstDatabase, file_id: HirFileId) -> Arc<HygieneFrame> {
489     Arc::new(HygieneFrame::new(db, file_id))
490 }
491
492 fn macro_expand_to(db: &dyn AstDatabase, id: MacroCallId) -> ExpandTo {
493     let loc: MacroCallLoc = db.lookup_intern_macro_call(id);
494     loc.kind.expand_to()
495 }
496
497 fn token_tree_to_syntax_node(
498     tt: &tt::Subtree,
499     expand_to: ExpandTo,
500 ) -> Result<(Parse<SyntaxNode>, mbe::TokenMap), ExpandError> {
501     let entry_point = match expand_to {
502         ExpandTo::Statements => mbe::TopEntryPoint::MacroStmts,
503         ExpandTo::Items => mbe::TopEntryPoint::MacroItems,
504         ExpandTo::Pattern => mbe::TopEntryPoint::Pattern,
505         ExpandTo::Type => mbe::TopEntryPoint::Type,
506         ExpandTo::Expr => mbe::TopEntryPoint::Expr,
507     };
508     mbe::token_tree_to_syntax_node(tt, entry_point)
509 }