1 //! Defines database & queries for macro expansion.
5 use base_db::{salsa, SourceDatabase};
8 use mbe::syntax_node_to_token_tree;
9 use rustc_hash::FxHashSet;
12 ast::{self, HasAttrs, HasDocComments},
13 AstNode, GreenNode, Parse, SyntaxNode, SyntaxToken, T,
17 ast_id_map::AstIdMap, fixup, hygiene::HygieneFrame, BuiltinAttrExpander, BuiltinDeriveExpander,
18 BuiltinFnLikeExpander, ExpandError, ExpandResult, ExpandTo, HirFileId, HirFileIdRepr,
19 MacroCallId, MacroCallKind, MacroCallLoc, MacroDefId, MacroDefKind, MacroFile,
23 /// Total limit on the number of tokens produced by any macro invocation.
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.
28 /// Actual max for `analysis-stats .` at some point: 30672.
29 static TOKEN_LIMIT: Limit = Limit::new(524_288);
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),
51 ) -> ExpandResult<tt::Subtree> {
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)
66 pub(crate) fn map_id_down(&self, id: tt::TokenId) -> tt::TokenId {
68 TokenExpander::DeclarativeMacro { mac, .. } => mac.map_id_down(id),
69 TokenExpander::Builtin(..)
70 | TokenExpander::BuiltinAttr(..)
71 | TokenExpander::BuiltinDerive(..)
72 | TokenExpander::ProcMacro(..) => id,
76 pub(crate) fn map_id_up(&self, id: tt::TokenId) -> (tt::TokenId, mbe::Origin) {
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),
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>;
92 /// Main public API -- parses a hir file, not caring whether it's a real
93 /// file or a macro expansion.
95 fn parse_or_expand(&self, file_id: HirFileId) -> Option<SyntaxNode>;
96 /// Implementation for the macro case.
97 fn parse_macro_expansion(
99 macro_file: MacroFile,
100 ) -> ExpandResult<Option<(Parse<SyntaxNode>, Arc<mbe::TokenMap>)>>;
102 /// Macro ids. That's probably the tricksiest bit in rust-analyzer, and the
103 /// reason why we use salsa at all.
105 /// We encode macro definitions into ids of macro calls, this what allows us
106 /// to be incremental.
108 fn intern_macro_call(&self, macro_call: MacroCallLoc) -> MacroCallId;
110 /// Lowers syntactic macro call to a token tree representation.
111 #[salsa::transparent]
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
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>;
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>;
134 fn hygiene_frame(&self, file_id: HirFileId) -> Arc<HygieneFrame>;
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
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();
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(
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())?;
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;
177 let shift = mbe::Shift::new(&tt);
178 shift.shift_all(&mut tree);
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)?);
189 (Some(tree), token_id)
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
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)
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 {
210 expander.expand(db, loc.krate, &tt, attr_arg.as_ref())
212 macro_def.expand(db, actual_macro_call, &tt)
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);
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))
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();
229 fn parse_or_expand(db: &dyn AstDatabase, file_id: HirFileId) -> Option<SyntaxNode> {
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())
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);
247 if let Some(err) = &result.err {
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);
254 // collect parent information for warning log
256 std::iter::successors(loc.kind.file_id().call_node(db), |it| it.file_id.call_node(db))
257 .map(|n| format!("{:#}", n.value))
262 "fail on macro_parse: (reason: {:?} macro_call: {:#}) parents: {}",
268 let tt = match result.value {
270 None => return ExpandResult { value: None, err: result.err },
273 let expand_to = macro_expand_to(db, macro_file.macro_call_id);
275 tracing::debug!("expanded = {}", tt.as_debug_string());
276 tracing::debug!("kind = {:?}", expand_to);
278 let (parse, rev_token_map) = token_tree_to_syntax_node(&tt, expand_to);
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) {
288 return ExpandResult::only_err(err);
291 if is_self_replicating(&node, &call_node.value) {
292 ExpandResult::only_err(err)
294 ExpandResult { value: Some((parse, Arc::new(rev_token_map))), err: Some(err) }
298 tracing::debug!("parse = {:?}", parse.syntax_node().kind());
299 ExpandResult { value: Some((parse, Arc::new(rev_token_map))), err: None }
305 db: &dyn AstDatabase,
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);
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(
323 if loc.def.is_proc_macro() {
324 // proc macros expect their inputs without parentheses, MBEs expect it with them included
328 Some(Arc::new((tt, tmap, fixups.undo_info)))
331 fn censor_for_macro_input(loc: &MacroCallLoc, node: &SyntaxNode) -> FxHashSet<SyntaxNode> {
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())?
339 .take(derive_attr_index as usize + 1)
341 .filter(|attr| attr.simple_name().as_deref() == Some("derive"))
342 .map(|it| it.syntax().clone())
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())
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());
369 matches!((first, last), (T!['('], T![')']) | (T!['['], T![']']) | (T!['{'], T!['}']));
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.
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);
382 Some(arg.green().into())
385 fn macro_def(db: &dyn AstDatabase, id: MacroDefId) -> Result<Arc<TokenExpander>, mbe::ParseError> {
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
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)
397 ast::Macro::MacroDef(macro_def) => {
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)
406 Ok(Arc::new(TokenExpander::DeclarativeMacro { mac, def_site_token_map }))
408 MacroDefKind::BuiltIn(expander, _) => Ok(Arc::new(TokenExpander::Builtin(expander))),
409 MacroDefKind::BuiltInAttr(expander, _) => {
410 Ok(Arc::new(TokenExpander::BuiltinAttr(expander)))
412 MacroDefKind::BuiltInDerive(expander, _) => {
413 Ok(Arc::new(TokenExpander::BuiltinDerive(expander)))
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()))
420 MacroDefKind::ProcMacro(expander, ..) => Ok(Arc::new(TokenExpander::ProcMacro(expander))),
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!
435 let macro_arg = match db.macro_arg(id) {
438 return ExpandResult::only_err(ExpandError::Other(
439 "Failed to lower macro args to token tree".into(),
444 let expander = match db.macro_def(loc.def) {
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).
450 return ExpandResult::only_err(ExpandError::Other(
451 format!("invalid macro definition: {}", err).into(),
455 let ExpandResult { value: mut tt, err } = expander.expand(db, id, ¯o_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(
461 "macro invocation exceeds token limit: produced {} tokens, limit is {}",
469 fixup::reverse_fixups(&mut tt, ¯o_arg.1, ¯o_arg.2);
471 ExpandResult { value: Some(Arc::new(tt)), err }
474 fn macro_expand_error(db: &dyn AstDatabase, macro_call: MacroCallId) -> Option<ExpandError> {
475 db.macro_expand(macro_call).err
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) {
483 return ExpandResult::only_err(ExpandError::Other("No arguments for proc-macro".into()))
487 let expander = match loc.def.kind {
488 MacroDefKind::ProcMacro(expander, ..) => expander,
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(¯o_arg.0).shift_all(&mut attr_args);
501 expander.expand(db, loc.krate, ¯o_arg.0, attr_arg.as_ref())
504 fn is_self_replicating(from: &SyntaxNode, to: &SyntaxNode) -> bool {
505 if diff(from, to).is_empty() {
508 if let Some(stmts) = ast::MacroStmts::cast(from.clone()) {
509 if stmts.statements().any(|stmt| diff(stmt.syntax(), to).is_empty()) {
512 if let Some(expr) = stmts.expr() {
513 if diff(expr.syntax(), to).is_empty() {
521 fn hygiene_frame(db: &dyn AstDatabase, file_id: HirFileId) -> Arc<HygieneFrame> {
522 Arc::new(HygieneFrame::new(db, file_id))
525 fn macro_expand_to(db: &dyn AstDatabase, id: MacroCallId) -> ExpandTo {
526 let loc: MacroCallLoc = db.lookup_intern_macro_call(id);
530 fn token_tree_to_syntax_node(
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,
541 mbe::token_tree_to_syntax_node(tt, entry_point)