1 //! Defines database & queries for macro expansion.
5 use base_db::{salsa, SourceDatabase};
8 use mbe::{syntax_node_to_token_tree, ExpandError, ExpandResult};
9 use rustc_hash::FxHashSet;
12 ast::{self, HasAttrs, HasDocComments},
13 AstNode, GreenNode, Parse, SyntaxNode, SyntaxToken, T,
17 ast_id_map::AstIdMap, hygiene::HygieneFrame, BuiltinAttrExpander, BuiltinDeriveExpander,
18 BuiltinFnLikeExpander, ExpandTo, HirFileId, HirFileIdRepr, MacroCallId, MacroCallKind,
19 MacroCallLoc, MacroDefId, MacroDefKind, MacroFile, ProcMacroExpander,
22 /// Total limit on the number of tokens produced by any macro invocation.
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.
27 /// Actual max for `analysis-stats .` at some point: 30672.
28 static TOKEN_LIMIT: Limit = Limit::new(524_288);
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),
50 ) -> mbe::ExpandResult<tt::Subtree> {
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)
65 pub(crate) fn map_id_down(&self, id: tt::TokenId) -> tt::TokenId {
67 TokenExpander::DeclarativeMacro { mac, .. } => mac.map_id_down(id),
68 TokenExpander::Builtin(..)
69 | TokenExpander::BuiltinAttr(..)
70 | TokenExpander::BuiltinDerive(..)
71 | TokenExpander::ProcMacro(..) => id,
75 pub(crate) fn map_id_up(&self, id: tt::TokenId) -> (tt::TokenId, mbe::Origin) {
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),
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>;
91 /// Main public API -- parses a hir file, not caring whether it's a real
92 /// file or a macro expansion.
94 fn parse_or_expand(&self, file_id: HirFileId) -> Option<SyntaxNode>;
95 /// Implementation for the macro case.
96 fn parse_macro_expansion(
98 macro_file: MacroFile,
99 ) -> ExpandResult<Option<(Parse<SyntaxNode>, Arc<mbe::TokenMap>)>>;
101 /// Macro ids. That's probably the tricksiest bit in rust-analyzer, and the
102 /// reason why we use salsa at all.
104 /// We encode macro definitions into ids of macro calls, this what allows us
105 /// to be incremental.
107 fn intern_macro_call(&self, macro_call: MacroCallLoc) -> MacroCallId;
109 /// Lowers syntactic macro call to a token tree representation.
110 #[salsa::transparent]
111 fn macro_arg(&self, id: MacroCallId) -> Option<Arc<(tt::Subtree, mbe::TokenMap)>>;
112 /// Extracts syntax node, corresponding to a macro call. That's a firewall
113 /// query, only typing in the macro call itself changes the returned
115 fn macro_arg_text(&self, id: MacroCallId) -> Option<GreenNode>;
116 /// Gets the expander for this macro. This compiles declarative macros, and
117 /// just fetches procedural ones.
118 fn macro_def(&self, id: MacroDefId) -> Result<Arc<TokenExpander>, mbe::ParseError>;
120 /// Expand macro call to a token tree. This query is LRUed (we keep 128 or so results in memory)
121 fn macro_expand(&self, macro_call: MacroCallId) -> ExpandResult<Option<Arc<tt::Subtree>>>;
122 /// Special case of the previous query for procedural macros. We can't LRU
123 /// proc macros, since they are not deterministic in general, and
124 /// non-determinism breaks salsa in a very, very, very bad way. @edwin0cheng
125 /// heroically debugged this once!
126 fn expand_proc_macro(&self, call: MacroCallId) -> ExpandResult<tt::Subtree>;
127 /// Firewall query that returns the error from the `macro_expand` query.
128 fn macro_expand_error(&self, macro_call: MacroCallId) -> Option<ExpandError>;
130 fn hygiene_frame(&self, file_id: HirFileId) -> Arc<HygieneFrame>;
133 /// This expands the given macro call, but with different arguments. This is
134 /// used for completion, where we want to see what 'would happen' if we insert a
135 /// token. The `token_to_map` mapped down into the expansion, with the mapped
137 pub fn expand_speculative(
138 db: &dyn AstDatabase,
139 actual_macro_call: MacroCallId,
140 speculative_args: &SyntaxNode,
141 token_to_map: SyntaxToken,
142 ) -> Option<(SyntaxNode, SyntaxToken)> {
143 let loc = db.lookup_intern_macro_call(actual_macro_call);
144 let macro_def = db.macro_def(loc.def).ok()?;
145 let token_range = token_to_map.text_range();
147 // Build the subtree and token mapping for the speculative args
148 let censor = censor_for_macro_input(&loc, &speculative_args);
149 let (mut tt, spec_args_tmap) =
150 mbe::syntax_node_to_token_tree_censored(&speculative_args, &censor);
152 let (attr_arg, token_id) = match loc.kind {
153 MacroCallKind::Attr { invoc_attr_index, .. } => {
154 // Attributes may have an input token tree, build the subtree and map for this as well
155 // then try finding a token id for our token if it is inside this input subtree.
156 let item = ast::Item::cast(speculative_args.clone())?;
158 .doc_comments_and_attrs()
159 .nth(invoc_attr_index as usize)
160 .and_then(Either::right)?;
161 match attr.token_tree() {
162 Some(token_tree) => {
163 let (mut tree, map) = syntax_node_to_token_tree(attr.token_tree()?.syntax());
164 tree.delimiter = None;
166 let shift = mbe::Shift::new(&tt);
167 shift.shift_all(&mut tree);
169 let token_id = if token_tree.syntax().text_range().contains_range(token_range) {
170 let attr_input_start =
171 token_tree.left_delimiter_token()?.text_range().start();
172 let range = token_range.checked_sub(attr_input_start)?;
173 let token_id = shift.shift(map.token_by_range(range)?);
178 (Some(tree), token_id)
185 let token_id = match token_id {
186 Some(token_id) => token_id,
187 // token wasn't inside an attribute input so it has to be in the general macro input
189 let range = token_range.checked_sub(speculative_args.text_range().start())?;
190 let token_id = spec_args_tmap.token_by_range(range)?;
191 macro_def.map_id_down(token_id)
195 // Do the actual expansion, we need to directly expand the proc macro due to the attribute args
196 // Otherwise the expand query will fetch the non speculative attribute args and pass those instead.
197 let speculative_expansion = if let MacroDefKind::ProcMacro(expander, ..) = loc.def.kind {
199 expander.expand(db, loc.krate, &tt, attr_arg.as_ref())
201 macro_def.expand(db, actual_macro_call, &tt)
204 let expand_to = macro_expand_to(db, actual_macro_call);
205 let (node, rev_tmap) = token_tree_to_syntax_node(&speculative_expansion.value, expand_to);
207 let range = rev_tmap.first_range_by_token(token_id, token_to_map.kind())?;
208 let token = node.syntax_node().covering_element(range).into_token()?;
209 Some((node.syntax_node(), token))
212 fn ast_id_map(db: &dyn AstDatabase, file_id: HirFileId) -> Arc<AstIdMap> {
213 let map = db.parse_or_expand(file_id).map(|it| AstIdMap::from_source(&it)).unwrap_or_default();
217 fn parse_or_expand(db: &dyn AstDatabase, file_id: HirFileId) -> Option<SyntaxNode> {
219 HirFileIdRepr::FileId(file_id) => Some(db.parse(file_id).tree().syntax().clone()),
220 HirFileIdRepr::MacroFile(macro_file) => {
221 // FIXME: Note how we convert from `Parse` to `SyntaxNode` here,
222 // forgetting about parse errors.
223 db.parse_macro_expansion(macro_file).value.map(|(it, _)| it.syntax_node())
228 fn parse_macro_expansion(
229 db: &dyn AstDatabase,
230 macro_file: MacroFile,
231 ) -> ExpandResult<Option<(Parse<SyntaxNode>, Arc<mbe::TokenMap>)>> {
232 let _p = profile::span("parse_macro_expansion");
233 let result = db.macro_expand(macro_file.macro_call_id);
235 if let Some(err) = &result.err {
237 // The final goal we would like to make all parse_macro success,
238 // such that the following log will not call anyway.
239 let loc: MacroCallLoc = db.lookup_intern_macro_call(macro_file.macro_call_id);
240 let node = loc.kind.to_node(db);
242 // collect parent information for warning log
244 std::iter::successors(loc.kind.file_id().call_node(db), |it| it.file_id.call_node(db))
245 .map(|n| format!("{:#}", n.value))
250 "fail on macro_parse: (reason: {:?} macro_call: {:#}) parents: {}",
256 let tt = match result.value {
258 None => return ExpandResult { value: None, err: result.err },
261 let expand_to = macro_expand_to(db, macro_file.macro_call_id);
263 tracing::debug!("expanded = {}", tt.as_debug_string());
264 tracing::debug!("kind = {:?}", expand_to);
266 let (parse, rev_token_map) = token_tree_to_syntax_node(&tt, expand_to);
270 // Safety check for recursive identity macro.
271 let node = parse.syntax_node();
272 let file: HirFileId = macro_file.into();
273 let call_node = match file.call_node(db) {
276 return ExpandResult::only_err(err);
279 if is_self_replicating(&node, &call_node.value) {
280 ExpandResult::only_err(err)
282 ExpandResult { value: Some((parse, Arc::new(rev_token_map))), err: Some(err) }
286 tracing::debug!("parse = {:?}", parse.syntax_node().kind());
287 ExpandResult { value: Some((parse, Arc::new(rev_token_map))), err: None }
292 fn macro_arg(db: &dyn AstDatabase, id: MacroCallId) -> Option<Arc<(tt::Subtree, mbe::TokenMap)>> {
293 let arg = db.macro_arg_text(id)?;
294 let loc = db.lookup_intern_macro_call(id);
296 let node = SyntaxNode::new_root(arg);
297 let censor = censor_for_macro_input(&loc, &node);
298 let (mut tt, tmap) = mbe::syntax_node_to_token_tree_censored(&node, &censor);
300 if loc.def.is_proc_macro() {
301 // proc macros expect their inputs without parentheses, MBEs expect it with them included
305 Some(Arc::new((tt, tmap)))
308 fn censor_for_macro_input(loc: &MacroCallLoc, node: &SyntaxNode) -> FxHashSet<SyntaxNode> {
310 let censor = match loc.kind {
311 MacroCallKind::FnLike { .. } => return None,
312 MacroCallKind::Derive { derive_attr_index, .. } => {
313 cov_mark::hit!(derive_censoring);
314 ast::Item::cast(node.clone())?
316 .take(derive_attr_index as usize + 1)
317 .filter(|attr| attr.simple_name().as_deref() == Some("derive"))
318 .map(|it| it.syntax().clone())
321 MacroCallKind::Attr { invoc_attr_index, .. } => {
322 cov_mark::hit!(attribute_macro_attr_censoring);
323 ast::Item::cast(node.clone())?
324 .doc_comments_and_attrs()
325 .nth(invoc_attr_index as usize)
326 .and_then(Either::right)
327 .map(|attr| attr.syntax().clone())
337 fn macro_arg_text(db: &dyn AstDatabase, id: MacroCallId) -> Option<GreenNode> {
338 let loc = db.lookup_intern_macro_call(id);
339 let arg = loc.kind.arg(db)?;
340 if matches!(loc.kind, MacroCallKind::FnLike { .. }) {
341 let first = arg.first_child_or_token().map_or(T![.], |it| it.kind());
342 let last = arg.last_child_or_token().map_or(T![.], |it| it.kind());
344 matches!((first, last), (T!['('], T![')']) | (T!['['], T![']']) | (T!['{'], T!['}']));
346 // Don't expand malformed (unbalanced) macro invocations. This is
347 // less than ideal, but trying to expand unbalanced macro calls
348 // sometimes produces pathological, deeply nested code which breaks
349 // all kinds of things.
351 // Some day, we'll have explicit recursion counters for all
352 // recursive things, at which point this code might be removed.
353 cov_mark::hit!(issue9358_bad_macro_stack_overflow);
357 Some(arg.green().into())
360 fn macro_def(db: &dyn AstDatabase, id: MacroDefId) -> Result<Arc<TokenExpander>, mbe::ParseError> {
362 MacroDefKind::Declarative(ast_id) => {
363 let (mac, def_site_token_map) = match ast_id.to_node(db) {
364 ast::Macro::MacroRules(macro_rules) => {
365 let arg = macro_rules
367 .ok_or_else(|| mbe::ParseError::Expected("expected a token tree".into()))?;
368 let (tt, def_site_token_map) = mbe::syntax_node_to_token_tree(arg.syntax());
369 let mac = mbe::DeclarativeMacro::parse_macro_rules(&tt)?;
370 (mac, def_site_token_map)
372 ast::Macro::MacroDef(macro_def) => {
375 .ok_or_else(|| mbe::ParseError::Expected("expected a token tree".into()))?;
376 let (tt, def_site_token_map) = mbe::syntax_node_to_token_tree(arg.syntax());
377 let mac = mbe::DeclarativeMacro::parse_macro2(&tt)?;
378 (mac, def_site_token_map)
381 Ok(Arc::new(TokenExpander::DeclarativeMacro { mac, def_site_token_map }))
383 MacroDefKind::BuiltIn(expander, _) => Ok(Arc::new(TokenExpander::Builtin(expander))),
384 MacroDefKind::BuiltInAttr(expander, _) => {
385 Ok(Arc::new(TokenExpander::BuiltinAttr(expander)))
387 MacroDefKind::BuiltInDerive(expander, _) => {
388 Ok(Arc::new(TokenExpander::BuiltinDerive(expander)))
390 MacroDefKind::BuiltInEager(..) => {
391 // FIXME: Return a random error here just to make the types align.
392 // This obviously should do something real instead.
393 Err(mbe::ParseError::UnexpectedToken("unexpected eager macro".to_string()))
395 MacroDefKind::ProcMacro(expander, ..) => Ok(Arc::new(TokenExpander::ProcMacro(expander))),
399 fn macro_expand(db: &dyn AstDatabase, id: MacroCallId) -> ExpandResult<Option<Arc<tt::Subtree>>> {
400 let _p = profile::span("macro_expand");
401 let loc: MacroCallLoc = db.lookup_intern_macro_call(id);
402 if let Some(eager) = &loc.eager {
403 return ExpandResult {
404 value: Some(eager.arg_or_expansion.clone()),
405 // FIXME: There could be errors here!
410 let macro_arg = match db.macro_arg(id) {
412 None => return ExpandResult::str_err("Failed to lower macro args to token tree".into()),
415 let expander = match db.macro_def(loc.def) {
417 // FIXME: This is weird -- we effectively report macro *definition*
418 // errors lazily, when we try to expand the macro. Instead, they should
419 // be reported at the definition site (when we construct a def map).
420 Err(err) => return ExpandResult::str_err(format!("invalid macro definition: {}", err)),
422 let ExpandResult { value: tt, err } = expander.expand(db, id, ¯o_arg.0);
423 // Set a hard limit for the expanded tt
424 let count = tt.count();
425 // XXX: Make ExpandResult a real error and use .map_err instead?
426 if TOKEN_LIMIT.check(count).is_err() {
427 return ExpandResult::str_err(format!(
428 "macro invocation exceeds token limit: produced {} tokens, limit is {}",
434 ExpandResult { value: Some(Arc::new(tt)), err }
437 fn macro_expand_error(db: &dyn AstDatabase, macro_call: MacroCallId) -> Option<ExpandError> {
438 db.macro_expand(macro_call).err
441 fn expand_proc_macro(db: &dyn AstDatabase, id: MacroCallId) -> ExpandResult<tt::Subtree> {
442 let loc: MacroCallLoc = db.lookup_intern_macro_call(id);
443 let macro_arg = match db.macro_arg(id) {
445 None => return ExpandResult::str_err("No arguments for proc-macro".to_string()),
448 let expander = match loc.def.kind {
449 MacroDefKind::ProcMacro(expander, ..) => expander,
453 let attr_arg = match &loc.kind {
454 MacroCallKind::Attr { attr_args, .. } => {
455 let mut attr_args = attr_args.0.clone();
456 mbe::Shift::new(¯o_arg.0).shift_all(&mut attr_args);
462 expander.expand(db, loc.krate, ¯o_arg.0, attr_arg.as_ref())
465 fn is_self_replicating(from: &SyntaxNode, to: &SyntaxNode) -> bool {
466 if diff(from, to).is_empty() {
469 if let Some(stmts) = ast::MacroStmts::cast(from.clone()) {
470 if stmts.statements().any(|stmt| diff(stmt.syntax(), to).is_empty()) {
473 if let Some(expr) = stmts.expr() {
474 if diff(expr.syntax(), to).is_empty() {
482 fn hygiene_frame(db: &dyn AstDatabase, file_id: HirFileId) -> Arc<HygieneFrame> {
483 Arc::new(HygieneFrame::new(db, file_id))
486 fn macro_expand_to(db: &dyn AstDatabase, id: MacroCallId) -> ExpandTo {
487 let loc: MacroCallLoc = db.lookup_intern_macro_call(id);
491 fn token_tree_to_syntax_node(
494 ) -> (Parse<SyntaxNode>, mbe::TokenMap) {
495 let entry_point = match expand_to {
496 ExpandTo::Statements => mbe::TopEntryPoint::MacroStmts,
497 ExpandTo::Items => mbe::TopEntryPoint::MacroItems,
498 ExpandTo::Pattern => mbe::TopEntryPoint::Pattern,
499 ExpandTo::Type => mbe::TopEntryPoint::Type,
500 ExpandTo::Expr => mbe::TopEntryPoint::Expr,
502 mbe::token_tree_to_syntax_node(tt, entry_point)