1 //! Defines database & queries for macro expansion.
5 use base_db::{salsa, SourceDatabase};
6 use mbe::{ExpandError, ExpandResult};
7 use parser::FragmentKind;
10 ast::{self, NameOwner},
11 AstNode, GreenNode, Parse, SyntaxNode, SyntaxToken,
15 ast_id_map::AstIdMap, hygiene::HygieneFrame, input::process_macro_input, BuiltinDeriveExpander,
16 BuiltinFnLikeExpander, EagerCallLoc, EagerMacroId, HirFileId, HirFileIdRepr, LazyMacroId,
17 MacroCallId, MacroCallLoc, MacroDefId, MacroDefKind, MacroFile, ProcMacroExpander,
20 /// Total limit on the number of tokens produced by any macro invocation.
22 /// If an invocation produces more tokens than this limit, it will not be stored in the database and
23 /// an error will be emitted.
24 const TOKEN_LIMIT: usize = 524288;
26 #[derive(Debug, Clone, Eq, PartialEq)]
27 pub enum TokenExpander {
28 /// Old-style `macro_rules`.
29 MacroRules { mac: mbe::MacroRules, def_site_token_map: mbe::TokenMap },
31 MacroDef { mac: mbe::MacroDef, def_site_token_map: mbe::TokenMap },
32 /// Stuff like `line!` and `file!`.
33 Builtin(BuiltinFnLikeExpander),
34 /// `derive(Copy)` and such.
35 BuiltinDerive(BuiltinDeriveExpander),
36 /// The thing we love the most here in rust-analyzer -- procedural macros.
37 ProcMacro(ProcMacroExpander),
46 ) -> mbe::ExpandResult<tt::Subtree> {
48 TokenExpander::MacroRules { mac, .. } => mac.expand(tt),
49 TokenExpander::MacroDef { mac, .. } => mac.expand(tt),
50 TokenExpander::Builtin(it) => it.expand(db, id, tt),
51 // FIXME switch these to ExpandResult as well
52 TokenExpander::BuiltinDerive(it) => it.expand(db, id, tt).into(),
53 TokenExpander::ProcMacro(_) => {
54 // We store the result in salsa db to prevent non-deterministic behavior in
55 // some proc-macro implementation
56 // See #4315 for details
57 db.expand_proc_macro(id.into()).into()
62 pub(crate) fn map_id_down(&self, id: tt::TokenId) -> tt::TokenId {
64 TokenExpander::MacroRules { mac, .. } => mac.map_id_down(id),
65 TokenExpander::MacroDef { mac, .. } => mac.map_id_down(id),
66 TokenExpander::Builtin(..)
67 | TokenExpander::BuiltinDerive(..)
68 | TokenExpander::ProcMacro(..) => id,
72 pub(crate) fn map_id_up(&self, id: tt::TokenId) -> (tt::TokenId, mbe::Origin) {
74 TokenExpander::MacroRules { mac, .. } => mac.map_id_up(id),
75 TokenExpander::MacroDef { mac, .. } => mac.map_id_up(id),
76 TokenExpander::Builtin(..)
77 | TokenExpander::BuiltinDerive(..)
78 | TokenExpander::ProcMacro(..) => (id, mbe::Origin::Call),
83 // FIXME: rename to ExpandDatabase
84 #[salsa::query_group(AstDatabaseStorage)]
85 pub trait AstDatabase: SourceDatabase {
86 fn ast_id_map(&self, file_id: HirFileId) -> Arc<AstIdMap>;
88 /// Main public API -- parsis a hir file, not caring whether it's a real
89 /// file or a macro expansion.
91 fn parse_or_expand(&self, file_id: HirFileId) -> Option<SyntaxNode>;
92 /// Implementation for the macro case.
93 fn parse_macro_expansion(
95 macro_file: MacroFile,
96 ) -> ExpandResult<Option<(Parse<SyntaxNode>, Arc<mbe::TokenMap>)>>;
98 /// Macro ids. That's probably the tricksiest bit in rust-analyzer, and the
99 /// reason why we use salsa at all.
101 /// We encode macro definitions into ids of macro calls, this what allows us
102 /// to be incremental.
104 fn intern_macro(&self, macro_call: MacroCallLoc) -> LazyMacroId;
105 /// Certain built-in macros are eager (`format!(concat!("file: ", file!(), "{}"")), 92`).
106 /// For them, we actually want to encode the whole token tree as an argument.
108 fn intern_eager_expansion(&self, eager: EagerCallLoc) -> EagerMacroId;
110 /// Lowers syntactic macro call to a token tree representation.
111 #[salsa::transparent]
112 fn macro_arg(&self, id: MacroCallId) -> Option<Arc<(tt::Subtree, mbe::TokenMap)>>;
113 /// Extracts syntax node, corresponding to a macro call. That's a firewall
114 /// query, only typing in the macro call itself changes the returned
116 fn macro_arg_text(&self, id: MacroCallId) -> Option<GreenNode>;
117 /// Gets the expander for this macro. This compiles declarative macros, and
118 /// just fetches procedural ones.
119 fn macro_def(&self, id: MacroDefId) -> Option<Arc<TokenExpander>>;
121 /// Expand macro call to a token tree. This query is LRUed (we keep 128 or so results in memory)
122 fn macro_expand(&self, macro_call: MacroCallId) -> ExpandResult<Option<Arc<tt::Subtree>>>;
123 /// Special case of the previous query for procedural macros. We can't LRU
124 /// proc macros, since they are not deterministic in general, and
125 /// non-determinism breaks salsa in a very, very, very bad way. @edwin0cheng
126 /// heroically debugged this once!
127 fn expand_proc_macro(&self, call: MacroCallId) -> Result<tt::Subtree, mbe::ExpandError>;
128 /// Firewall query that returns the error from the `macro_expand` query.
129 fn macro_expand_error(&self, macro_call: MacroCallId) -> Option<ExpandError>;
131 fn hygiene_frame(&self, file_id: HirFileId) -> Arc<HygieneFrame>;
134 /// This expands the given macro call, but with different arguments. This is
135 /// used for completion, where we want to see what 'would happen' if we insert a
136 /// token. The `token_to_map` mapped down into the expansion, with the mapped
138 pub fn expand_hypothetical(
139 db: &dyn AstDatabase,
140 actual_macro_call: MacroCallId,
141 hypothetical_args: &ast::TokenTree,
142 token_to_map: SyntaxToken,
143 ) -> Option<(SyntaxNode, SyntaxToken)> {
144 let (tt, tmap_1) = mbe::syntax_node_to_token_tree(hypothetical_args.syntax());
146 token_to_map.text_range().checked_sub(hypothetical_args.syntax().text_range().start())?;
147 let token_id = tmap_1.token_by_range(range)?;
149 let lazy_id = match actual_macro_call {
150 MacroCallId::LazyMacro(id) => id,
151 MacroCallId::EagerMacro(_) => return None,
155 let loc = db.lookup_intern_macro(lazy_id);
156 db.macro_def(loc.def)?
159 let hypothetical_expansion = macro_def.expand(db, lazy_id, &tt);
161 let fragment_kind = macro_fragment_kind(db, actual_macro_call);
164 mbe::token_tree_to_syntax_node(&hypothetical_expansion.value, fragment_kind).ok()?;
166 let token_id = macro_def.map_id_down(token_id);
167 let range = tmap_2.range_by_token(token_id)?.by_kind(token_to_map.kind())?;
168 let token = node.syntax_node().covering_element(range).into_token()?;
169 Some((node.syntax_node(), token))
172 fn ast_id_map(db: &dyn AstDatabase, file_id: HirFileId) -> Arc<AstIdMap> {
173 let map = db.parse_or_expand(file_id).map(|it| AstIdMap::from_source(&it)).unwrap_or_default();
177 fn parse_or_expand(db: &dyn AstDatabase, file_id: HirFileId) -> Option<SyntaxNode> {
179 HirFileIdRepr::FileId(file_id) => Some(db.parse(file_id).tree().syntax().clone()),
180 HirFileIdRepr::MacroFile(macro_file) => {
181 db.parse_macro_expansion(macro_file).value.map(|(it, _)| it.syntax_node())
186 fn parse_macro_expansion(
187 db: &dyn AstDatabase,
188 macro_file: MacroFile,
189 ) -> ExpandResult<Option<(Parse<SyntaxNode>, Arc<mbe::TokenMap>)>> {
190 let _p = profile::span("parse_macro_expansion");
191 let result = db.macro_expand(macro_file.macro_call_id);
193 if let Some(err) = &result.err {
195 // The final goal we would like to make all parse_macro success,
196 // such that the following log will not call anyway.
197 match macro_file.macro_call_id {
198 MacroCallId::LazyMacro(id) => {
199 let loc: MacroCallLoc = db.lookup_intern_macro(id);
200 let node = loc.kind.node(db);
202 // collect parent information for warning log
203 let parents = std::iter::successors(loc.kind.file_id().call_node(db), |it| {
204 it.file_id.call_node(db)
206 .map(|n| format!("{:#}", n.value))
211 "fail on macro_parse: (reason: {:?} macro_call: {:#}) parents: {}",
218 log::warn!("fail on macro_parse: (reason: {:?})", err);
222 let tt = match result.value {
224 None => return ExpandResult { value: None, err: result.err },
227 let fragment_kind = macro_fragment_kind(db, macro_file.macro_call_id);
229 log::debug!("expanded = {}", tt.as_debug_string());
230 log::debug!("kind = {:?}", fragment_kind);
232 let (parse, rev_token_map) = match mbe::token_tree_to_syntax_node(&tt, fragment_kind) {
236 "failed to parse expanstion to {:?} = {}",
240 return ExpandResult::only_err(err);
246 // Safety check for recursive identity macro.
247 let node = parse.syntax_node();
248 let file: HirFileId = macro_file.into();
249 let call_node = match file.call_node(db) {
252 return ExpandResult::only_err(err);
255 if is_self_replicating(&node, &call_node.value) {
256 return ExpandResult::only_err(err);
258 ExpandResult { value: Some((parse, Arc::new(rev_token_map))), err: Some(err) }
262 log::debug!("parse = {:?}", parse.syntax_node().kind());
263 ExpandResult { value: Some((parse, Arc::new(rev_token_map))), err: None }
268 fn macro_arg(db: &dyn AstDatabase, id: MacroCallId) -> Option<Arc<(tt::Subtree, mbe::TokenMap)>> {
269 let arg = db.macro_arg_text(id)?;
270 let (mut tt, tmap) = mbe::syntax_node_to_token_tree(&SyntaxNode::new_root(arg));
272 if let MacroCallId::LazyMacro(id) = id {
273 let loc: MacroCallLoc = db.lookup_intern_macro(id);
274 if loc.def.is_proc_macro() {
275 // proc macros expect their inputs without parentheses, MBEs expect it with them included
280 Some(Arc::new((tt, tmap)))
283 fn macro_arg_text(db: &dyn AstDatabase, id: MacroCallId) -> Option<GreenNode> {
285 MacroCallId::LazyMacro(id) => id,
286 MacroCallId::EagerMacro(_id) => {
287 // FIXME: support macro_arg for eager macro
291 let loc = db.lookup_intern_macro(id);
292 let arg = loc.kind.arg(db)?;
293 let arg = process_macro_input(db, arg, id);
294 Some(arg.green().into())
297 fn macro_def(db: &dyn AstDatabase, id: MacroDefId) -> Option<Arc<TokenExpander>> {
299 MacroDefKind::Declarative(ast_id) => match ast_id.to_node(db) {
300 ast::Macro::MacroRules(macro_rules) => {
301 let arg = macro_rules.token_tree()?;
302 let (tt, def_site_token_map) = mbe::ast_to_token_tree(&arg);
303 let mac = match mbe::MacroRules::parse(&tt) {
306 let name = macro_rules.name().map(|n| n.to_string()).unwrap_or_default();
307 log::warn!("fail on macro_def parse ({}): {:?} {:#?}", name, err, tt);
311 Some(Arc::new(TokenExpander::MacroRules { mac, def_site_token_map }))
313 ast::Macro::MacroDef(macro_def) => {
314 let arg = macro_def.body()?;
315 let (tt, def_site_token_map) = mbe::ast_to_token_tree(&arg);
316 let mac = match mbe::MacroDef::parse(&tt) {
319 let name = macro_def.name().map(|n| n.to_string()).unwrap_or_default();
320 log::warn!("fail on macro_def parse ({}): {:?} {:#?}", name, err, tt);
324 Some(Arc::new(TokenExpander::MacroDef { mac, def_site_token_map }))
327 MacroDefKind::BuiltIn(expander, _) => Some(Arc::new(TokenExpander::Builtin(expander))),
328 MacroDefKind::BuiltInDerive(expander, _) => {
329 Some(Arc::new(TokenExpander::BuiltinDerive(expander)))
331 MacroDefKind::BuiltInEager(..) => None,
332 MacroDefKind::ProcMacro(expander, ..) => Some(Arc::new(TokenExpander::ProcMacro(expander))),
336 fn macro_expand(db: &dyn AstDatabase, id: MacroCallId) -> ExpandResult<Option<Arc<tt::Subtree>>> {
337 macro_expand_with_arg(db, id, None)
340 fn macro_expand_error(db: &dyn AstDatabase, macro_call: MacroCallId) -> Option<ExpandError> {
341 db.macro_expand(macro_call).err
344 fn macro_expand_with_arg(
345 db: &dyn AstDatabase,
347 arg: Option<Arc<(tt::Subtree, mbe::TokenMap)>>,
348 ) -> ExpandResult<Option<Arc<tt::Subtree>>> {
349 let _p = profile::span("macro_expand");
350 let lazy_id = match id {
351 MacroCallId::LazyMacro(id) => id,
352 MacroCallId::EagerMacro(id) => {
354 return ExpandResult::str_err(
355 "hypothetical macro expansion not implemented for eager macro".to_owned(),
358 return ExpandResult {
359 value: Some(db.lookup_intern_eager_expansion(id).subtree),
360 // FIXME: There could be errors here!
367 let loc = db.lookup_intern_macro(lazy_id);
368 let macro_arg = match arg.or_else(|| db.macro_arg(id)) {
370 None => return ExpandResult::str_err("Fail to args in to tt::TokenTree".into()),
373 let macro_rules = match db.macro_def(loc.def) {
375 None => return ExpandResult::str_err("Fail to find macro definition".into()),
377 let ExpandResult { value: tt, err } = macro_rules.expand(db, lazy_id, ¯o_arg.0);
378 // Set a hard limit for the expanded tt
379 let count = tt.count();
380 if count > TOKEN_LIMIT {
381 return ExpandResult::str_err(format!(
382 "macro invocation exceeds token limit: produced {} tokens, limit is {}",
387 ExpandResult { value: Some(Arc::new(tt)), err }
390 fn expand_proc_macro(
391 db: &dyn AstDatabase,
393 ) -> Result<tt::Subtree, mbe::ExpandError> {
394 let lazy_id = match id {
395 MacroCallId::LazyMacro(id) => id,
396 MacroCallId::EagerMacro(_) => unreachable!(),
399 let loc = db.lookup_intern_macro(lazy_id);
400 let macro_arg = match db.macro_arg(id) {
404 tt::ExpansionError::Unknown("No arguments for proc-macro".to_string()).into()
409 let expander = match loc.def.kind {
410 MacroDefKind::ProcMacro(expander, ..) => expander,
414 expander.expand(db, loc.krate, ¯o_arg.0)
417 fn is_self_replicating(from: &SyntaxNode, to: &SyntaxNode) -> bool {
418 if diff(from, to).is_empty() {
421 if let Some(stmts) = ast::MacroStmts::cast(from.clone()) {
422 if stmts.statements().any(|stmt| diff(stmt.syntax(), to).is_empty()) {
425 if let Some(expr) = stmts.expr() {
426 if diff(expr.syntax(), to).is_empty() {
434 fn hygiene_frame(db: &dyn AstDatabase, file_id: HirFileId) -> Arc<HygieneFrame> {
435 Arc::new(HygieneFrame::new(db, file_id))
438 fn macro_fragment_kind(db: &dyn AstDatabase, id: MacroCallId) -> FragmentKind {
440 MacroCallId::LazyMacro(id) => {
441 let loc: MacroCallLoc = db.lookup_intern_macro(id);
442 loc.kind.fragment_kind()
444 MacroCallId::EagerMacro(id) => {
445 let loc: EagerCallLoc = db.lookup_intern_eager_expansion(id);