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