]> git.lizzy.rs Git - rust.git/blob - crates/hir_expand/src/db.rs
Speculatively expand attributes in completions
[rust.git] / crates / hir_expand / src / db.rs
1 //! Defines database & queries for macro expansion.
2
3 use std::sync::Arc;
4
5 use base_db::{salsa, SourceDatabase};
6 use itertools::Itertools;
7 use limit::Limit;
8 use mbe::{ExpandError, ExpandResult};
9 use syntax::{
10     algo::diff,
11     ast::{self, AttrsOwner, NameOwner},
12     AstNode, GreenNode, Parse, SyntaxNode, SyntaxToken, TextRange, T,
13 };
14
15 use crate::{
16     ast_id_map::AstIdMap, hygiene::HygieneFrame, BuiltinAttrExpander, BuiltinDeriveExpander,
17     BuiltinFnLikeExpander, ExpandTo, HirFileId, HirFileIdRepr, MacroCallId, MacroCallKind,
18     MacroCallLoc, MacroDefId, MacroDefKind, MacroFile, ProcMacroExpander,
19 };
20
21 /// Total limit on the number of tokens produced by any macro invocation.
22 ///
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.
25 ///
26 /// Actual max for `analysis-stats .` at some point: 30672.
27 static TOKEN_LIMIT: Limit = Limit::new(524_288);
28
29 #[derive(Debug, Clone, Eq, PartialEq)]
30 pub enum TokenExpander {
31     /// Old-style `macro_rules`.
32     MacroRules { mac: mbe::MacroRules, def_site_token_map: mbe::TokenMap },
33     /// AKA macros 2.0.
34     MacroDef { mac: mbe::MacroDef, def_site_token_map: mbe::TokenMap },
35     /// Stuff like `line!` and `file!`.
36     Builtin(BuiltinFnLikeExpander),
37     /// `global_allocator` and such.
38     BuiltinAttr(BuiltinAttrExpander),
39     /// `derive(Copy)` and such.
40     BuiltinDerive(BuiltinDeriveExpander),
41     /// The thing we love the most here in rust-analyzer -- procedural macros.
42     ProcMacro(ProcMacroExpander),
43 }
44
45 impl TokenExpander {
46     fn expand(
47         &self,
48         db: &dyn AstDatabase,
49         id: MacroCallId,
50         tt: &tt::Subtree,
51     ) -> mbe::ExpandResult<tt::Subtree> {
52         match self {
53             TokenExpander::MacroRules { mac, .. } => mac.expand(tt),
54             TokenExpander::MacroDef { mac, .. } => mac.expand(tt),
55             TokenExpander::Builtin(it) => it.expand(db, id, tt),
56             TokenExpander::BuiltinAttr(it) => it.expand(db, id, tt),
57             TokenExpander::BuiltinDerive(it) => it.expand(db, id, tt),
58             TokenExpander::ProcMacro(_) => {
59                 // We store the result in salsa db to prevent non-deterministic behavior in
60                 // some proc-macro implementation
61                 // See #4315 for details
62                 db.expand_proc_macro(id)
63             }
64         }
65     }
66
67     pub(crate) fn map_id_down(&self, id: tt::TokenId) -> tt::TokenId {
68         match self {
69             TokenExpander::MacroRules { mac, .. } => mac.map_id_down(id),
70             TokenExpander::MacroDef { mac, .. } => mac.map_id_down(id),
71             TokenExpander::Builtin(..)
72             | TokenExpander::BuiltinAttr(..)
73             | TokenExpander::BuiltinDerive(..)
74             | TokenExpander::ProcMacro(..) => id,
75         }
76     }
77
78     pub(crate) fn map_id_up(&self, id: tt::TokenId) -> (tt::TokenId, mbe::Origin) {
79         match self {
80             TokenExpander::MacroRules { mac, .. } => mac.map_id_up(id),
81             TokenExpander::MacroDef { mac, .. } => mac.map_id_up(id),
82             TokenExpander::Builtin(..)
83             | TokenExpander::BuiltinAttr(..)
84             | TokenExpander::BuiltinDerive(..)
85             | TokenExpander::ProcMacro(..) => (id, mbe::Origin::Call),
86         }
87     }
88 }
89
90 // FIXME: rename to ExpandDatabase
91 #[salsa::query_group(AstDatabaseStorage)]
92 pub trait AstDatabase: SourceDatabase {
93     fn ast_id_map(&self, file_id: HirFileId) -> Arc<AstIdMap>;
94
95     /// Main public API -- parses a hir file, not caring whether it's a real
96     /// file or a macro expansion.
97     #[salsa::transparent]
98     fn parse_or_expand(&self, file_id: HirFileId) -> Option<SyntaxNode>;
99     /// Implementation for the macro case.
100     fn parse_macro_expansion(
101         &self,
102         macro_file: MacroFile,
103     ) -> ExpandResult<Option<(Parse<SyntaxNode>, Arc<mbe::TokenMap>)>>;
104
105     /// Macro ids. That's probably the tricksiest bit in rust-analyzer, and the
106     /// reason why we use salsa at all.
107     ///
108     /// We encode macro definitions into ids of macro calls, this what allows us
109     /// to be incremental.
110     #[salsa::interned]
111     fn intern_macro(&self, macro_call: MacroCallLoc) -> MacroCallId;
112
113     /// Lowers syntactic macro call to a token tree representation.
114     #[salsa::transparent]
115     fn macro_arg(&self, id: MacroCallId) -> Option<Arc<(tt::Subtree, mbe::TokenMap)>>;
116     /// Extracts syntax node, corresponding to a macro call. That's a firewall
117     /// query, only typing in the macro call itself changes the returned
118     /// subtree.
119     fn macro_arg_text(&self, id: MacroCallId) -> Option<GreenNode>;
120     /// Gets the expander for this macro. This compiles declarative macros, and
121     /// just fetches procedural ones.
122     fn macro_def(&self, id: MacroDefId) -> Option<Arc<TokenExpander>>;
123
124     /// Expand macro call to a token tree. This query is LRUed (we keep 128 or so results in memory)
125     fn macro_expand(&self, macro_call: MacroCallId) -> ExpandResult<Option<Arc<tt::Subtree>>>;
126     /// Special case of the previous query for procedural macros. We can't LRU
127     /// proc macros, since they are not deterministic in general, and
128     /// non-determinism breaks salsa in a very, very, very bad way. @edwin0cheng
129     /// heroically debugged this once!
130     fn expand_proc_macro(&self, call: MacroCallId) -> ExpandResult<tt::Subtree>;
131     /// Firewall query that returns the error from the `macro_expand` query.
132     fn macro_expand_error(&self, macro_call: MacroCallId) -> Option<ExpandError>;
133
134     fn hygiene_frame(&self, file_id: HirFileId) -> Arc<HygieneFrame>;
135 }
136
137 /// This expands the given macro call, but with different arguments. This is
138 /// used for completion, where we want to see what 'would happen' if we insert a
139 /// token. The `token_to_map` mapped down into the expansion, with the mapped
140 /// token returned.
141 pub fn expand_speculative(
142     db: &dyn AstDatabase,
143     actual_macro_call: MacroCallId,
144     speculative_args: &SyntaxNode,
145     token_to_map: SyntaxToken,
146 ) -> Option<(SyntaxNode, SyntaxToken)> {
147     let loc = db.lookup_intern_macro(actual_macro_call);
148     let macro_def = db.macro_def(loc.def)?;
149
150     // Fetch token id in the speculative args
151     let censor = censor_for_macro_input(&loc, &speculative_args);
152     let (tt, args_tmap) = mbe::syntax_node_to_token_tree_censored(&speculative_args, censor);
153     let range = token_to_map.text_range().checked_sub(speculative_args.text_range().start())?;
154     let token_id = args_tmap.token_by_range(range)?;
155
156     let speculative_expansion = if let MacroDefKind::ProcMacro(expander, ..) = loc.def.kind {
157         let attr_arg = match &loc.kind {
158             // FIXME make attr arg speculative as well
159             MacroCallKind::Attr { attr_args, .. } => {
160                 let mut attr_args = attr_args.0.clone();
161                 mbe::Shift::new(&tt).shift_all(&mut attr_args);
162                 Some(attr_args)
163             }
164             _ => None,
165         };
166
167         expander.expand(db, loc.krate, &tt, attr_arg.as_ref())
168     } else {
169         macro_def.expand(db, actual_macro_call, &tt)
170     };
171
172     let expand_to = macro_expand_to(db, actual_macro_call);
173     let (node, rev_tmap) =
174         token_tree_to_syntax_node(&speculative_expansion.value, expand_to).ok()?;
175
176     let token_id = macro_def.map_id_down(token_id);
177     let range = rev_tmap.first_range_by_token(token_id, token_to_map.kind())?;
178     let token = node.syntax_node().covering_element(range).into_token()?;
179     Some((node.syntax_node(), token))
180 }
181
182 fn ast_id_map(db: &dyn AstDatabase, file_id: HirFileId) -> Arc<AstIdMap> {
183     let map = db.parse_or_expand(file_id).map(|it| AstIdMap::from_source(&it)).unwrap_or_default();
184     Arc::new(map)
185 }
186
187 fn parse_or_expand(db: &dyn AstDatabase, file_id: HirFileId) -> Option<SyntaxNode> {
188     match file_id.0 {
189         HirFileIdRepr::FileId(file_id) => Some(db.parse(file_id).tree().syntax().clone()),
190         HirFileIdRepr::MacroFile(macro_file) => {
191             db.parse_macro_expansion(macro_file).value.map(|(it, _)| it.syntax_node())
192         }
193     }
194 }
195
196 fn parse_macro_expansion(
197     db: &dyn AstDatabase,
198     macro_file: MacroFile,
199 ) -> ExpandResult<Option<(Parse<SyntaxNode>, Arc<mbe::TokenMap>)>> {
200     let _p = profile::span("parse_macro_expansion");
201     let result = db.macro_expand(macro_file.macro_call_id);
202
203     if let Some(err) = &result.err {
204         // Note:
205         // The final goal we would like to make all parse_macro success,
206         // such that the following log will not call anyway.
207         let loc: MacroCallLoc = db.lookup_intern_macro(macro_file.macro_call_id);
208         let node = loc.kind.to_node(db);
209
210         // collect parent information for warning log
211         let parents =
212             std::iter::successors(loc.kind.file_id().call_node(db), |it| it.file_id.call_node(db))
213                 .map(|n| format!("{:#}", n.value))
214                 .collect::<Vec<_>>()
215                 .join("\n");
216
217         tracing::warn!(
218             "fail on macro_parse: (reason: {:?} macro_call: {:#}) parents: {}",
219             err,
220             node.value,
221             parents
222         );
223     }
224     let tt = match result.value {
225         Some(tt) => tt,
226         None => return ExpandResult { value: None, err: result.err },
227     };
228
229     let expand_to = macro_expand_to(db, macro_file.macro_call_id);
230
231     tracing::debug!("expanded = {}", tt.as_debug_string());
232     tracing::debug!("kind = {:?}", expand_to);
233
234     let (parse, rev_token_map) = match token_tree_to_syntax_node(&tt, expand_to) {
235         Ok(it) => it,
236         Err(err) => {
237             tracing::debug!(
238                 "failed to parse expansion to {:?} = {}",
239                 expand_to,
240                 tt.as_debug_string()
241             );
242             return ExpandResult::only_err(err);
243         }
244     };
245
246     match result.err {
247         Some(err) => {
248             // Safety check for recursive identity macro.
249             let node = parse.syntax_node();
250             let file: HirFileId = macro_file.into();
251             let call_node = match file.call_node(db) {
252                 Some(it) => it,
253                 None => {
254                     return ExpandResult::only_err(err);
255                 }
256             };
257             if is_self_replicating(&node, &call_node.value) {
258                 ExpandResult::only_err(err)
259             } else {
260                 ExpandResult { value: Some((parse, Arc::new(rev_token_map))), err: Some(err) }
261             }
262         }
263         None => {
264             tracing::debug!("parse = {:?}", parse.syntax_node().kind());
265             ExpandResult { value: Some((parse, Arc::new(rev_token_map))), err: None }
266         }
267     }
268 }
269
270 fn macro_arg(db: &dyn AstDatabase, id: MacroCallId) -> Option<Arc<(tt::Subtree, mbe::TokenMap)>> {
271     let arg = db.macro_arg_text(id)?;
272     let loc = db.lookup_intern_macro(id);
273
274     let node = SyntaxNode::new_root(arg);
275     let censor = censor_for_macro_input(&loc, &node);
276     let (mut tt, tmap) = mbe::syntax_node_to_token_tree_censored(&node, censor);
277
278     if loc.def.is_proc_macro() {
279         // proc macros expect their inputs without parentheses, MBEs expect it with them included
280         tt.delimiter = None;
281     }
282
283     Some(Arc::new((tt, tmap)))
284 }
285
286 fn censor_for_macro_input(loc: &MacroCallLoc, node: &SyntaxNode) -> Option<TextRange> {
287     match loc.kind {
288         MacroCallKind::FnLike { .. } => None,
289         MacroCallKind::Derive { derive_attr_index, .. } => match ast::Item::cast(node.clone()) {
290             Some(item) => item
291                 .attrs()
292                 .map(|attr| attr.syntax().text_range())
293                 .take(derive_attr_index as usize + 1)
294                 .fold1(TextRange::cover),
295             None => None,
296         },
297         MacroCallKind::Attr { invoc_attr_index, .. } => match ast::Item::cast(node.clone()) {
298             Some(item) => {
299                 item.attrs().nth(invoc_attr_index as usize).map(|attr| attr.syntax().text_range())
300             }
301             None => None,
302         },
303     }
304 }
305
306 fn macro_arg_text(db: &dyn AstDatabase, id: MacroCallId) -> Option<GreenNode> {
307     let loc = db.lookup_intern_macro(id);
308     let arg = loc.kind.arg(db)?;
309     if matches!(loc.kind, MacroCallKind::FnLike { .. }) {
310         let first = arg.first_child_or_token().map_or(T![.], |it| it.kind());
311         let last = arg.last_child_or_token().map_or(T![.], |it| it.kind());
312         let well_formed_tt =
313             matches!((first, last), (T!['('], T![')']) | (T!['['], T![']']) | (T!['{'], T!['}']));
314         if !well_formed_tt {
315             // Don't expand malformed (unbalanced) macro invocations. This is
316             // less than ideal, but trying to expand unbalanced  macro calls
317             // sometimes produces pathological, deeply nested code which breaks
318             // all kinds of things.
319             //
320             // Some day, we'll have explicit recursion counters for all
321             // recursive things, at which point this code might be removed.
322             cov_mark::hit!(issue9358_bad_macro_stack_overflow);
323             return None;
324         }
325     }
326     Some(arg.green().into())
327 }
328
329 fn macro_def(db: &dyn AstDatabase, id: MacroDefId) -> Option<Arc<TokenExpander>> {
330     match id.kind {
331         MacroDefKind::Declarative(ast_id) => match ast_id.to_node(db) {
332             ast::Macro::MacroRules(macro_rules) => {
333                 let arg = macro_rules.token_tree()?;
334                 let (tt, def_site_token_map) = mbe::syntax_node_to_token_tree(arg.syntax());
335                 let mac = match mbe::MacroRules::parse(&tt) {
336                     Ok(it) => it,
337                     Err(err) => {
338                         let name = macro_rules.name().map(|n| n.to_string()).unwrap_or_default();
339                         tracing::warn!("fail on macro_def parse ({}): {:?} {:#?}", name, err, tt);
340                         return None;
341                     }
342                 };
343                 Some(Arc::new(TokenExpander::MacroRules { mac, def_site_token_map }))
344             }
345             ast::Macro::MacroDef(macro_def) => {
346                 let arg = macro_def.body()?;
347                 let (tt, def_site_token_map) = mbe::syntax_node_to_token_tree(arg.syntax());
348                 let mac = match mbe::MacroDef::parse(&tt) {
349                     Ok(it) => it,
350                     Err(err) => {
351                         let name = macro_def.name().map(|n| n.to_string()).unwrap_or_default();
352                         tracing::warn!("fail on macro_def parse ({}): {:?} {:#?}", name, err, tt);
353                         return None;
354                     }
355                 };
356                 Some(Arc::new(TokenExpander::MacroDef { mac, def_site_token_map }))
357             }
358         },
359         MacroDefKind::BuiltIn(expander, _) => Some(Arc::new(TokenExpander::Builtin(expander))),
360         MacroDefKind::BuiltInAttr(expander, _) => {
361             Some(Arc::new(TokenExpander::BuiltinAttr(expander)))
362         }
363         MacroDefKind::BuiltInDerive(expander, _) => {
364             Some(Arc::new(TokenExpander::BuiltinDerive(expander)))
365         }
366         MacroDefKind::BuiltInEager(..) => None,
367         MacroDefKind::ProcMacro(expander, ..) => Some(Arc::new(TokenExpander::ProcMacro(expander))),
368     }
369 }
370
371 fn macro_expand(db: &dyn AstDatabase, id: MacroCallId) -> ExpandResult<Option<Arc<tt::Subtree>>> {
372     let _p = profile::span("macro_expand");
373     let loc: MacroCallLoc = db.lookup_intern_macro(id);
374     if let Some(eager) = &loc.eager {
375         return ExpandResult {
376             value: Some(eager.arg_or_expansion.clone()),
377             // FIXME: There could be errors here!
378             err: None,
379         };
380     }
381
382     let macro_arg = match db.macro_arg(id) {
383         Some(it) => it,
384         None => return ExpandResult::str_err("Failed to lower macro args to token tree".into()),
385     };
386
387     let expander = match db.macro_def(loc.def) {
388         Some(it) => it,
389         None => return ExpandResult::str_err("Failed to find macro definition".into()),
390     };
391     let ExpandResult { value: tt, err } = expander.expand(db, id, &macro_arg.0);
392     // Set a hard limit for the expanded tt
393     let count = tt.count();
394     // XXX: Make ExpandResult a real error and use .map_err instead?
395     if TOKEN_LIMIT.check(count).is_err() {
396         return ExpandResult::str_err(format!(
397             "macro invocation exceeds token limit: produced {} tokens, limit is {}",
398             count,
399             TOKEN_LIMIT.inner(),
400         ));
401     }
402
403     ExpandResult { value: Some(Arc::new(tt)), err }
404 }
405
406 fn macro_expand_error(db: &dyn AstDatabase, macro_call: MacroCallId) -> Option<ExpandError> {
407     db.macro_expand(macro_call).err
408 }
409
410 fn expand_proc_macro(db: &dyn AstDatabase, id: MacroCallId) -> ExpandResult<tt::Subtree> {
411     let loc: MacroCallLoc = db.lookup_intern_macro(id);
412     let macro_arg = match db.macro_arg(id) {
413         Some(it) => it,
414         None => return ExpandResult::str_err("No arguments for proc-macro".to_string()),
415     };
416
417     let expander = match loc.def.kind {
418         MacroDefKind::ProcMacro(expander, ..) => expander,
419         _ => unreachable!(),
420     };
421
422     let attr_arg = match &loc.kind {
423         MacroCallKind::Attr { attr_args, .. } => {
424             let mut attr_args = attr_args.0.clone();
425             mbe::Shift::new(&macro_arg.0).shift_all(&mut attr_args);
426             Some(attr_args)
427         }
428         _ => None,
429     };
430
431     expander.expand(db, loc.krate, &macro_arg.0, attr_arg.as_ref())
432 }
433
434 fn is_self_replicating(from: &SyntaxNode, to: &SyntaxNode) -> bool {
435     if diff(from, to).is_empty() {
436         return true;
437     }
438     if let Some(stmts) = ast::MacroStmts::cast(from.clone()) {
439         if stmts.statements().any(|stmt| diff(stmt.syntax(), to).is_empty()) {
440             return true;
441         }
442         if let Some(expr) = stmts.expr() {
443             if diff(expr.syntax(), to).is_empty() {
444                 return true;
445             }
446         }
447     }
448     false
449 }
450
451 fn hygiene_frame(db: &dyn AstDatabase, file_id: HirFileId) -> Arc<HygieneFrame> {
452     Arc::new(HygieneFrame::new(db, file_id))
453 }
454
455 fn macro_expand_to(db: &dyn AstDatabase, id: MacroCallId) -> ExpandTo {
456     let loc: MacroCallLoc = db.lookup_intern_macro(id);
457     loc.kind.expand_to()
458 }
459
460 fn token_tree_to_syntax_node(
461     tt: &tt::Subtree,
462     expand_to: ExpandTo,
463 ) -> Result<(Parse<SyntaxNode>, mbe::TokenMap), ExpandError> {
464     let entry_point = match expand_to {
465         ExpandTo::Statements => mbe::ParserEntryPoint::Statements,
466         ExpandTo::Items => mbe::ParserEntryPoint::Items,
467         ExpandTo::Pattern => mbe::ParserEntryPoint::Pattern,
468         ExpandTo::Type => mbe::ParserEntryPoint::Type,
469         ExpandTo::Expr => mbe::ParserEntryPoint::Expr,
470     };
471     mbe::token_tree_to_syntax_node(tt, entry_point)
472 }