1 //! Defines database & queries for macro expansion.
5 use base_db::{salsa, SourceDatabase};
7 use mbe::{syntax_node_to_token_tree, ExpandError, ExpandResult};
8 use rustc_hash::FxHashSet;
11 ast::{self, HasAttrs},
12 AstNode, GreenNode, Parse, SyntaxNode, SyntaxToken, T,
16 ast_id_map::AstIdMap, hygiene::HygieneFrame, BuiltinAttrExpander, BuiltinDeriveExpander,
17 BuiltinFnLikeExpander, ExpandTo, HirFileId, HirFileIdRepr, MacroCallId, MacroCallKind,
18 MacroCallLoc, MacroDefId, MacroDefKind, MacroFile, ProcMacroExpander,
21 /// Total limit on the number of tokens produced by any macro invocation.
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.
26 /// Actual max for `analysis-stats .` at some point: 30672.
27 static TOKEN_LIMIT: Limit = Limit::new(524_288);
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),
49 ) -> mbe::ExpandResult<tt::Subtree> {
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)
64 pub(crate) fn map_id_down(&self, id: tt::TokenId) -> tt::TokenId {
66 TokenExpander::DeclarativeMacro { mac, .. } => mac.map_id_down(id),
67 TokenExpander::Builtin(..)
68 | TokenExpander::BuiltinAttr(..)
69 | TokenExpander::BuiltinDerive(..)
70 | TokenExpander::ProcMacro(..) => id,
74 pub(crate) fn map_id_up(&self, id: tt::TokenId) -> (tt::TokenId, mbe::Origin) {
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),
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>;
90 /// Main public API -- parses a hir file, not caring whether it's a real
91 /// file or a macro expansion.
93 fn parse_or_expand(&self, file_id: HirFileId) -> Option<SyntaxNode>;
94 /// Implementation for the macro case.
95 fn parse_macro_expansion(
97 macro_file: MacroFile,
98 ) -> ExpandResult<Option<(Parse<SyntaxNode>, Arc<mbe::TokenMap>)>>;
100 /// Macro ids. That's probably the tricksiest bit in rust-analyzer, and the
101 /// reason why we use salsa at all.
103 /// We encode macro definitions into ids of macro calls, this what allows us
104 /// to be incremental.
106 fn intern_macro_call(&self, macro_call: MacroCallLoc) -> MacroCallId;
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
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>;
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>;
129 fn hygiene_frame(&self, file_id: HirFileId) -> Arc<HygieneFrame>;
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
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();
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);
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;
162 let shift = mbe::Shift::new(&tt);
163 shift.shift_all(&mut tree);
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)?);
174 (Some(tree), token_id)
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
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)
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 {
195 expander.expand(db, loc.krate, &tt, attr_arg.as_ref())
197 macro_def.expand(db, actual_macro_call, &tt)
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()?;
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))
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();
214 fn parse_or_expand(db: &dyn AstDatabase, file_id: HirFileId) -> Option<SyntaxNode> {
216 HirFileIdRepr::FileId(file_id) => Some(db.parse(file_id).tree().syntax().clone()),
217 HirFileIdRepr::MacroFile(macro_file) => {
218 db.parse_macro_expansion(macro_file).value.map(|(it, _)| it.syntax_node())
223 fn parse_macro_expansion(
224 db: &dyn AstDatabase,
225 macro_file: MacroFile,
226 ) -> ExpandResult<Option<(Parse<SyntaxNode>, Arc<mbe::TokenMap>)>> {
227 let _p = profile::span("parse_macro_expansion");
228 let result = db.macro_expand(macro_file.macro_call_id);
230 if let Some(err) = &result.err {
232 // The final goal we would like to make all parse_macro success,
233 // such that the following log will not call anyway.
234 let loc: MacroCallLoc = db.lookup_intern_macro_call(macro_file.macro_call_id);
235 let node = loc.kind.to_node(db);
237 // collect parent information for warning log
239 std::iter::successors(loc.kind.file_id().call_node(db), |it| it.file_id.call_node(db))
240 .map(|n| format!("{:#}", n.value))
245 "fail on macro_parse: (reason: {:?} macro_call: {:#}) parents: {}",
251 let tt = match result.value {
253 None => return ExpandResult { value: None, err: result.err },
256 let expand_to = macro_expand_to(db, macro_file.macro_call_id);
258 tracing::debug!("expanded = {}", tt.as_debug_string());
259 tracing::debug!("kind = {:?}", expand_to);
261 let (parse, rev_token_map) = match token_tree_to_syntax_node(&tt, expand_to) {
265 "failed to parse expansion to {:?} = {}",
269 return ExpandResult::only_err(err);
275 // Safety check for recursive identity macro.
276 let node = parse.syntax_node();
277 let file: HirFileId = macro_file.into();
278 let call_node = match file.call_node(db) {
281 return ExpandResult::only_err(err);
284 if is_self_replicating(&node, &call_node.value) {
285 ExpandResult::only_err(err)
287 ExpandResult { value: Some((parse, Arc::new(rev_token_map))), err: Some(err) }
291 tracing::debug!("parse = {:?}", parse.syntax_node().kind());
292 ExpandResult { value: Some((parse, Arc::new(rev_token_map))), err: None }
297 fn macro_arg(db: &dyn AstDatabase, id: MacroCallId) -> Option<Arc<(tt::Subtree, mbe::TokenMap)>> {
298 let arg = db.macro_arg_text(id)?;
299 let loc = db.lookup_intern_macro_call(id);
301 let node = SyntaxNode::new_root(arg);
302 let censor = censor_for_macro_input(&loc, &node);
303 let (mut tt, tmap) = mbe::syntax_node_to_token_tree_censored(&node, &censor);
305 if loc.def.is_proc_macro() {
306 // proc macros expect their inputs without parentheses, MBEs expect it with them included
310 Some(Arc::new((tt, tmap)))
313 fn censor_for_macro_input(loc: &MacroCallLoc, node: &SyntaxNode) -> FxHashSet<SyntaxNode> {
315 let censor = match loc.kind {
316 MacroCallKind::FnLike { .. } => return None,
317 MacroCallKind::Derive { derive_attr_index, .. } => {
318 cov_mark::hit!(derive_censoring);
319 ast::Item::cast(node.clone())?
321 .take(derive_attr_index as usize + 1)
322 .filter(|attr| attr.simple_name().as_deref() == Some("derive"))
323 .map(|it| it.syntax().clone())
326 MacroCallKind::Attr { invoc_attr_index, .. } => {
327 cov_mark::hit!(attribute_macro_attr_censoring);
328 ast::Item::cast(node.clone())?
330 .nth(invoc_attr_index as usize)
331 .map(|attr| attr.syntax().clone())
341 fn macro_arg_text(db: &dyn AstDatabase, id: MacroCallId) -> Option<GreenNode> {
342 let loc = db.lookup_intern_macro_call(id);
343 let arg = loc.kind.arg(db)?;
344 if matches!(loc.kind, MacroCallKind::FnLike { .. }) {
345 let first = arg.first_child_or_token().map_or(T![.], |it| it.kind());
346 let last = arg.last_child_or_token().map_or(T![.], |it| it.kind());
348 matches!((first, last), (T!['('], T![')']) | (T!['['], T![']']) | (T!['{'], T!['}']));
350 // Don't expand malformed (unbalanced) macro invocations. This is
351 // less than ideal, but trying to expand unbalanced macro calls
352 // sometimes produces pathological, deeply nested code which breaks
353 // all kinds of things.
355 // Some day, we'll have explicit recursion counters for all
356 // recursive things, at which point this code might be removed.
357 cov_mark::hit!(issue9358_bad_macro_stack_overflow);
361 Some(arg.green().into())
364 fn macro_def(db: &dyn AstDatabase, id: MacroDefId) -> Result<Arc<TokenExpander>, mbe::ParseError> {
366 MacroDefKind::Declarative(ast_id) => {
367 let (mac, def_site_token_map) = match ast_id.to_node(db) {
368 ast::Macro::MacroRules(macro_rules) => {
369 let arg = macro_rules
371 .ok_or_else(|| mbe::ParseError::Expected("expected a token tree".into()))?;
372 let (tt, def_site_token_map) = mbe::syntax_node_to_token_tree(arg.syntax());
373 let mac = mbe::DeclarativeMacro::parse_macro_rules(&tt)?;
374 (mac, def_site_token_map)
376 ast::Macro::MacroDef(macro_def) => {
379 .ok_or_else(|| mbe::ParseError::Expected("expected a token tree".into()))?;
380 let (tt, def_site_token_map) = mbe::syntax_node_to_token_tree(arg.syntax());
381 let mac = mbe::DeclarativeMacro::parse_macro2(&tt)?;
382 (mac, def_site_token_map)
385 Ok(Arc::new(TokenExpander::DeclarativeMacro { mac, def_site_token_map }))
387 MacroDefKind::BuiltIn(expander, _) => Ok(Arc::new(TokenExpander::Builtin(expander))),
388 MacroDefKind::BuiltInAttr(expander, _) => {
389 Ok(Arc::new(TokenExpander::BuiltinAttr(expander)))
391 MacroDefKind::BuiltInDerive(expander, _) => {
392 Ok(Arc::new(TokenExpander::BuiltinDerive(expander)))
394 MacroDefKind::BuiltInEager(..) => {
395 // FIXME: Return a random error here just to make the types align.
396 // This obviously should do something real instead.
397 Err(mbe::ParseError::UnexpectedToken("unexpected eager macro".to_string()))
399 MacroDefKind::ProcMacro(expander, ..) => Ok(Arc::new(TokenExpander::ProcMacro(expander))),
403 fn macro_expand(db: &dyn AstDatabase, id: MacroCallId) -> ExpandResult<Option<Arc<tt::Subtree>>> {
404 let _p = profile::span("macro_expand");
405 let loc: MacroCallLoc = db.lookup_intern_macro_call(id);
406 if let Some(eager) = &loc.eager {
407 return ExpandResult {
408 value: Some(eager.arg_or_expansion.clone()),
409 // FIXME: There could be errors here!
414 let macro_arg = match db.macro_arg(id) {
416 None => return ExpandResult::str_err("Failed to lower macro args to token tree".into()),
419 let expander = match db.macro_def(loc.def) {
421 // FIXME: This is weird -- we effectively report macro *definition*
422 // errors lazily, when we try to expand the macro. Instead, they should
423 // be reported at the definition site (when we construct a def map).
424 Err(err) => return ExpandResult::str_err(format!("invalid macro definition: {}", err)),
426 let ExpandResult { value: tt, err } = expander.expand(db, id, ¯o_arg.0);
427 // Set a hard limit for the expanded tt
428 let count = tt.count();
429 // XXX: Make ExpandResult a real error and use .map_err instead?
430 if TOKEN_LIMIT.check(count).is_err() {
431 return ExpandResult::str_err(format!(
432 "macro invocation exceeds token limit: produced {} tokens, limit is {}",
438 ExpandResult { value: Some(Arc::new(tt)), err }
441 fn macro_expand_error(db: &dyn AstDatabase, macro_call: MacroCallId) -> Option<ExpandError> {
442 db.macro_expand(macro_call).err
445 fn expand_proc_macro(db: &dyn AstDatabase, id: MacroCallId) -> ExpandResult<tt::Subtree> {
446 let loc: MacroCallLoc = db.lookup_intern_macro_call(id);
447 let macro_arg = match db.macro_arg(id) {
449 None => return ExpandResult::str_err("No arguments for proc-macro".to_string()),
452 let expander = match loc.def.kind {
453 MacroDefKind::ProcMacro(expander, ..) => expander,
457 let attr_arg = match &loc.kind {
458 MacroCallKind::Attr { attr_args, .. } => {
459 let mut attr_args = attr_args.0.clone();
460 mbe::Shift::new(¯o_arg.0).shift_all(&mut attr_args);
466 expander.expand(db, loc.krate, ¯o_arg.0, attr_arg.as_ref())
469 fn is_self_replicating(from: &SyntaxNode, to: &SyntaxNode) -> bool {
470 if diff(from, to).is_empty() {
473 if let Some(stmts) = ast::MacroStmts::cast(from.clone()) {
474 if stmts.statements().any(|stmt| diff(stmt.syntax(), to).is_empty()) {
477 if let Some(expr) = stmts.expr() {
478 if diff(expr.syntax(), to).is_empty() {
486 fn hygiene_frame(db: &dyn AstDatabase, file_id: HirFileId) -> Arc<HygieneFrame> {
487 Arc::new(HygieneFrame::new(db, file_id))
490 fn macro_expand_to(db: &dyn AstDatabase, id: MacroCallId) -> ExpandTo {
491 let loc: MacroCallLoc = db.lookup_intern_macro_call(id);
495 fn token_tree_to_syntax_node(
498 ) -> Result<(Parse<SyntaxNode>, mbe::TokenMap), ExpandError> {
499 let entry_point = match expand_to {
500 ExpandTo::Statements => mbe::TopEntryPoint::MacroStmts,
501 ExpandTo::Items => mbe::TopEntryPoint::MacroItems,
502 ExpandTo::Pattern => mbe::TopEntryPoint::Pattern,
503 ExpandTo::Type => mbe::TopEntryPoint::Type,
504 ExpandTo::Expr => mbe::TopEntryPoint::Expr,
506 mbe::token_tree_to_syntax_node(tt, entry_point)