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, BuiltinDeriveExpander, BuiltinFnLikeExpander,
16 EagerCallLoc, EagerMacroId, HirFileId, HirFileIdRepr, LazyMacroId, MacroCallId, MacroCallLoc,
17 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 (tt, tmap) = mbe::syntax_node_to_token_tree(&SyntaxNode::new_root(arg));
271 Some(Arc::new((tt, tmap)))
274 fn macro_arg_text(db: &dyn AstDatabase, id: MacroCallId) -> Option<GreenNode> {
276 MacroCallId::LazyMacro(id) => id,
277 MacroCallId::EagerMacro(_id) => {
278 // FIXME: support macro_arg for eager macro
282 let loc = db.lookup_intern_macro(id);
283 let arg = loc.kind.arg(db)?;
284 Some(arg.green().into())
287 fn macro_def(db: &dyn AstDatabase, id: MacroDefId) -> Option<Arc<TokenExpander>> {
289 MacroDefKind::Declarative(ast_id) => match ast_id.to_node(db) {
290 ast::Macro::MacroRules(macro_rules) => {
291 let arg = macro_rules.token_tree()?;
292 let (tt, def_site_token_map) = mbe::ast_to_token_tree(&arg);
293 let mac = match mbe::MacroRules::parse(&tt) {
296 let name = macro_rules.name().map(|n| n.to_string()).unwrap_or_default();
297 log::warn!("fail on macro_def parse ({}): {:?} {:#?}", name, err, tt);
301 Some(Arc::new(TokenExpander::MacroRules { mac, def_site_token_map }))
303 ast::Macro::MacroDef(macro_def) => {
304 let arg = macro_def.body()?;
305 let (tt, def_site_token_map) = mbe::ast_to_token_tree(&arg);
306 let mac = match mbe::MacroDef::parse(&tt) {
309 let name = macro_def.name().map(|n| n.to_string()).unwrap_or_default();
310 log::warn!("fail on macro_def parse ({}): {:?} {:#?}", name, err, tt);
314 Some(Arc::new(TokenExpander::MacroDef { mac, def_site_token_map }))
317 MacroDefKind::BuiltIn(expander, _) => Some(Arc::new(TokenExpander::Builtin(expander))),
318 MacroDefKind::BuiltInDerive(expander, _) => {
319 Some(Arc::new(TokenExpander::BuiltinDerive(expander)))
321 MacroDefKind::BuiltInEager(..) => None,
322 MacroDefKind::ProcMacro(expander, ..) => Some(Arc::new(TokenExpander::ProcMacro(expander))),
326 fn macro_expand(db: &dyn AstDatabase, id: MacroCallId) -> ExpandResult<Option<Arc<tt::Subtree>>> {
327 macro_expand_with_arg(db, id, None)
330 fn macro_expand_error(db: &dyn AstDatabase, macro_call: MacroCallId) -> Option<ExpandError> {
331 db.macro_expand(macro_call).err
334 fn macro_expand_with_arg(
335 db: &dyn AstDatabase,
337 arg: Option<Arc<(tt::Subtree, mbe::TokenMap)>>,
338 ) -> ExpandResult<Option<Arc<tt::Subtree>>> {
339 let _p = profile::span("macro_expand");
340 let lazy_id = match id {
341 MacroCallId::LazyMacro(id) => id,
342 MacroCallId::EagerMacro(id) => {
344 return ExpandResult::str_err(
345 "hypothetical macro expansion not implemented for eager macro".to_owned(),
348 return ExpandResult {
349 value: Some(db.lookup_intern_eager_expansion(id).subtree),
350 // FIXME: There could be errors here!
357 let loc = db.lookup_intern_macro(lazy_id);
358 let macro_arg = match arg.or_else(|| db.macro_arg(id)) {
360 None => return ExpandResult::str_err("Fail to args in to tt::TokenTree".into()),
363 let macro_rules = match db.macro_def(loc.def) {
365 None => return ExpandResult::str_err("Fail to find macro definition".into()),
367 let ExpandResult { value: tt, err } = macro_rules.expand(db, lazy_id, ¯o_arg.0);
368 // Set a hard limit for the expanded tt
369 let count = tt.count();
370 if count > TOKEN_LIMIT {
371 return ExpandResult::str_err(format!(
372 "macro invocation exceeds token limit: produced {} tokens, limit is {}",
377 ExpandResult { value: Some(Arc::new(tt)), err }
380 fn expand_proc_macro(
381 db: &dyn AstDatabase,
383 ) -> Result<tt::Subtree, mbe::ExpandError> {
384 let lazy_id = match id {
385 MacroCallId::LazyMacro(id) => id,
386 MacroCallId::EagerMacro(_) => unreachable!(),
389 let loc = db.lookup_intern_macro(lazy_id);
390 let macro_arg = match db.macro_arg(id) {
394 tt::ExpansionError::Unknown("No arguments for proc-macro".to_string()).into()
399 let expander = match loc.def.kind {
400 MacroDefKind::ProcMacro(expander, ..) => expander,
404 expander.expand(db, loc.krate, ¯o_arg.0)
407 fn is_self_replicating(from: &SyntaxNode, to: &SyntaxNode) -> bool {
408 if diff(from, to).is_empty() {
411 if let Some(stmts) = ast::MacroStmts::cast(from.clone()) {
412 if stmts.statements().any(|stmt| diff(stmt.syntax(), to).is_empty()) {
415 if let Some(expr) = stmts.expr() {
416 if diff(expr.syntax(), to).is_empty() {
424 fn hygiene_frame(db: &dyn AstDatabase, file_id: HirFileId) -> Arc<HygieneFrame> {
425 Arc::new(HygieneFrame::new(db, file_id))
428 fn macro_fragment_kind(db: &dyn AstDatabase, id: MacroCallId) -> FragmentKind {
430 MacroCallId::LazyMacro(id) => {
431 let loc: MacroCallLoc = db.lookup_intern_macro(id);
432 loc.kind.fragment_kind()
434 MacroCallId::EagerMacro(id) => {
435 let loc: EagerCallLoc = db.lookup_intern_eager_expansion(id);