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