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, HirFileId, HirFileIdRepr, MacroCallId, MacroCallLoc, MacroDefId,
17 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) -> MacroCallId;
106 /// Lowers syntactic macro call to a token tree representation.
107 #[salsa::transparent]
108 fn macro_arg(&self, id: MacroCallId) -> Option<Arc<(tt::Subtree, mbe::TokenMap)>>;
109 /// Extracts syntax node, corresponding to a macro call. That's a firewall
110 /// query, only typing in the macro call itself changes the returned
112 fn macro_arg_text(&self, id: MacroCallId) -> Option<GreenNode>;
113 /// Gets the expander for this macro. This compiles declarative macros, and
114 /// just fetches procedural ones.
115 fn macro_def(&self, id: MacroDefId) -> Option<Arc<TokenExpander>>;
117 /// Expand macro call to a token tree. This query is LRUed (we keep 128 or so results in memory)
118 fn macro_expand(&self, macro_call: MacroCallId) -> ExpandResult<Option<Arc<tt::Subtree>>>;
119 /// Special case of the previous query for procedural macros. We can't LRU
120 /// proc macros, since they are not deterministic in general, and
121 /// non-determinism breaks salsa in a very, very, very bad way. @edwin0cheng
122 /// heroically debugged this once!
123 fn expand_proc_macro(&self, call: MacroCallId) -> Result<tt::Subtree, mbe::ExpandError>;
124 /// Firewall query that returns the error from the `macro_expand` query.
125 fn macro_expand_error(&self, macro_call: MacroCallId) -> Option<ExpandError>;
127 fn hygiene_frame(&self, file_id: HirFileId) -> Arc<HygieneFrame>;
130 /// This expands the given macro call, but with different arguments. This is
131 /// used for completion, where we want to see what 'would happen' if we insert a
132 /// token. The `token_to_map` mapped down into the expansion, with the mapped
134 pub fn expand_speculative(
135 db: &dyn AstDatabase,
136 actual_macro_call: MacroCallId,
137 speculative_args: &ast::TokenTree,
138 token_to_map: SyntaxToken,
139 ) -> Option<(SyntaxNode, SyntaxToken)> {
140 let (tt, tmap_1) = mbe::syntax_node_to_token_tree(speculative_args.syntax());
142 token_to_map.text_range().checked_sub(speculative_args.syntax().text_range().start())?;
143 let token_id = tmap_1.token_by_range(range)?;
146 let loc: MacroCallLoc = db.lookup_intern_macro(actual_macro_call);
147 db.macro_def(loc.def)?
150 let speculative_expansion = macro_def.expand(db, actual_macro_call, &tt);
152 let fragment_kind = macro_fragment_kind(db, actual_macro_call);
155 mbe::token_tree_to_syntax_node(&speculative_expansion.value, fragment_kind).ok()?;
157 let token_id = macro_def.map_id_down(token_id);
158 let range = tmap_2.range_by_token(token_id)?.by_kind(token_to_map.kind())?;
159 let token = node.syntax_node().covering_element(range).into_token()?;
160 Some((node.syntax_node(), token))
163 fn ast_id_map(db: &dyn AstDatabase, file_id: HirFileId) -> Arc<AstIdMap> {
164 let map = db.parse_or_expand(file_id).map(|it| AstIdMap::from_source(&it)).unwrap_or_default();
168 fn parse_or_expand(db: &dyn AstDatabase, file_id: HirFileId) -> Option<SyntaxNode> {
170 HirFileIdRepr::FileId(file_id) => Some(db.parse(file_id).tree().syntax().clone()),
171 HirFileIdRepr::MacroFile(macro_file) => {
172 db.parse_macro_expansion(macro_file).value.map(|(it, _)| it.syntax_node())
177 fn parse_macro_expansion(
178 db: &dyn AstDatabase,
179 macro_file: MacroFile,
180 ) -> ExpandResult<Option<(Parse<SyntaxNode>, Arc<mbe::TokenMap>)>> {
181 let _p = profile::span("parse_macro_expansion");
182 let result = db.macro_expand(macro_file.macro_call_id);
184 if let Some(err) = &result.err {
186 // The final goal we would like to make all parse_macro success,
187 // such that the following log will not call anyway.
188 let loc: MacroCallLoc = db.lookup_intern_macro(macro_file.macro_call_id);
189 let node = loc.kind.node(db);
191 // collect parent information for warning log
193 std::iter::successors(loc.kind.file_id().call_node(db), |it| it.file_id.call_node(db))
194 .map(|n| format!("{:#}", n.value))
199 "fail on macro_parse: (reason: {:?} macro_call: {:#}) parents: {}",
205 let tt = match result.value {
207 None => return ExpandResult { value: None, err: result.err },
210 let fragment_kind = macro_fragment_kind(db, macro_file.macro_call_id);
212 log::debug!("expanded = {}", tt.as_debug_string());
213 log::debug!("kind = {:?}", fragment_kind);
215 let (parse, rev_token_map) = match mbe::token_tree_to_syntax_node(&tt, fragment_kind) {
219 "failed to parse expanstion to {:?} = {}",
223 return ExpandResult::only_err(err);
229 // Safety check for recursive identity macro.
230 let node = parse.syntax_node();
231 let file: HirFileId = macro_file.into();
232 let call_node = match file.call_node(db) {
235 return ExpandResult::only_err(err);
238 if is_self_replicating(&node, &call_node.value) {
239 return ExpandResult::only_err(err);
241 ExpandResult { value: Some((parse, Arc::new(rev_token_map))), err: Some(err) }
245 log::debug!("parse = {:?}", parse.syntax_node().kind());
246 ExpandResult { value: Some((parse, Arc::new(rev_token_map))), err: None }
251 fn macro_arg(db: &dyn AstDatabase, id: MacroCallId) -> Option<Arc<(tt::Subtree, mbe::TokenMap)>> {
252 let arg = db.macro_arg_text(id)?;
253 let (mut tt, tmap) = mbe::syntax_node_to_token_tree(&SyntaxNode::new_root(arg));
255 let loc: MacroCallLoc = db.lookup_intern_macro(id);
256 if loc.def.is_proc_macro() {
257 // proc macros expect their inputs without parentheses, MBEs expect it with them included
261 Some(Arc::new((tt, tmap)))
264 fn macro_arg_text(db: &dyn AstDatabase, id: MacroCallId) -> Option<GreenNode> {
265 let loc = db.lookup_intern_macro(id);
266 let arg = loc.kind.arg(db)?;
267 let arg = process_macro_input(db, arg, id);
268 Some(arg.green().into())
271 fn macro_def(db: &dyn AstDatabase, id: MacroDefId) -> Option<Arc<TokenExpander>> {
273 MacroDefKind::Declarative(ast_id) => match ast_id.to_node(db) {
274 ast::Macro::MacroRules(macro_rules) => {
275 let arg = macro_rules.token_tree()?;
276 let (tt, def_site_token_map) = mbe::ast_to_token_tree(&arg);
277 let mac = match mbe::MacroRules::parse(&tt) {
280 let name = macro_rules.name().map(|n| n.to_string()).unwrap_or_default();
281 log::warn!("fail on macro_def parse ({}): {:?} {:#?}", name, err, tt);
285 Some(Arc::new(TokenExpander::MacroRules { mac, def_site_token_map }))
287 ast::Macro::MacroDef(macro_def) => {
288 let arg = macro_def.body()?;
289 let (tt, def_site_token_map) = mbe::ast_to_token_tree(&arg);
290 let mac = match mbe::MacroDef::parse(&tt) {
293 let name = macro_def.name().map(|n| n.to_string()).unwrap_or_default();
294 log::warn!("fail on macro_def parse ({}): {:?} {:#?}", name, err, tt);
298 Some(Arc::new(TokenExpander::MacroDef { mac, def_site_token_map }))
301 MacroDefKind::BuiltIn(expander, _) => Some(Arc::new(TokenExpander::Builtin(expander))),
302 MacroDefKind::BuiltInDerive(expander, _) => {
303 Some(Arc::new(TokenExpander::BuiltinDerive(expander)))
305 MacroDefKind::BuiltInEager(..) => None,
306 MacroDefKind::ProcMacro(expander, ..) => Some(Arc::new(TokenExpander::ProcMacro(expander))),
310 fn macro_expand(db: &dyn AstDatabase, id: MacroCallId) -> ExpandResult<Option<Arc<tt::Subtree>>> {
311 macro_expand_with_arg(db, id, None)
314 fn macro_expand_error(db: &dyn AstDatabase, macro_call: MacroCallId) -> Option<ExpandError> {
315 db.macro_expand(macro_call).err
318 fn macro_expand_with_arg(
319 db: &dyn AstDatabase,
321 arg: Option<Arc<(tt::Subtree, mbe::TokenMap)>>,
322 ) -> ExpandResult<Option<Arc<tt::Subtree>>> {
323 let _p = profile::span("macro_expand");
324 let loc: MacroCallLoc = db.lookup_intern_macro(id);
325 if let Some(eager) = &loc.eager {
327 return ExpandResult::str_err(
328 "speculative macro expansion not implemented for eager macro".to_owned(),
331 return ExpandResult {
332 value: Some(eager.arg_or_expansion.clone()),
333 // FIXME: There could be errors here!
339 let macro_arg = match arg.or_else(|| db.macro_arg(id)) {
341 None => return ExpandResult::str_err("Fail to args in to tt::TokenTree".into()),
344 let macro_rules = match db.macro_def(loc.def) {
346 None => return ExpandResult::str_err("Fail to find macro definition".into()),
348 let ExpandResult { value: tt, err } = macro_rules.expand(db, id, ¯o_arg.0);
349 // Set a hard limit for the expanded tt
350 let count = tt.count();
351 if count > TOKEN_LIMIT {
352 return ExpandResult::str_err(format!(
353 "macro invocation exceeds token limit: produced {} tokens, limit is {}",
358 ExpandResult { value: Some(Arc::new(tt)), err }
361 fn expand_proc_macro(
362 db: &dyn AstDatabase,
364 ) -> Result<tt::Subtree, mbe::ExpandError> {
365 let loc: MacroCallLoc = db.lookup_intern_macro(id);
366 let macro_arg = match db.macro_arg(id) {
370 tt::ExpansionError::Unknown("No arguments for proc-macro".to_string()).into()
375 let expander = match loc.def.kind {
376 MacroDefKind::ProcMacro(expander, ..) => expander,
380 expander.expand(db, loc.krate, ¯o_arg.0)
383 fn is_self_replicating(from: &SyntaxNode, to: &SyntaxNode) -> bool {
384 if diff(from, to).is_empty() {
387 if let Some(stmts) = ast::MacroStmts::cast(from.clone()) {
388 if stmts.statements().any(|stmt| diff(stmt.syntax(), to).is_empty()) {
391 if let Some(expr) = stmts.expr() {
392 if diff(expr.syntax(), to).is_empty() {
400 fn hygiene_frame(db: &dyn AstDatabase, file_id: HirFileId) -> Arc<HygieneFrame> {
401 Arc::new(HygieneFrame::new(db, file_id))
404 fn macro_fragment_kind(db: &dyn AstDatabase, id: MacroCallId) -> FragmentKind {
405 let loc: MacroCallLoc = db.lookup_intern_macro(id);
406 loc.kind.fragment_kind()