rust-analyzer/crates/mbe/src/expander.rs

178 lines
5.9 KiB
Rust
Raw Normal View History

2019-09-02 15:51:03 +00:00
//! This module takes a (parsed) definition of `macro_rules` invocation, a
//! `tt::TokenTree` representing an argument of macro invocation, and produces a
//! `tt::TokenTree` for the result of the expansion.
mod matcher;
mod transcriber;
use rustc_hash::FxHashMap;
2020-08-12 16:26:51 +00:00
use syntax::SmolStr;
2019-01-31 10:59:25 +00:00
2020-03-14 19:24:18 +00:00
use crate::{ExpandError, ExpandResult};
2021-01-25 21:15:47 +00:00
pub(crate) fn expand_rules(
rules: &[crate::Rule],
input: &tt::Subtree,
) -> ExpandResult<tt::Subtree> {
2020-03-15 13:37:30 +00:00
let mut match_: Option<(matcher::Match, &crate::Rule)> = None;
for rule in rules {
let new_match = matcher::match_(&rule.lhs, input);
2020-03-16 17:38:10 +00:00
if new_match.err.is_none() {
2020-03-16 17:04:07 +00:00
// If we find a rule that applies without errors, we're done.
// Unconditionally returning the transcription here makes the
// `test_repeat_bad_var` test fail.
2020-11-26 15:04:23 +00:00
let ExpandResult { value, err: transcribe_err } =
2020-03-16 11:22:10 +00:00
transcriber::transcribe(&rule.rhs, &new_match.bindings);
2020-03-15 13:37:30 +00:00
if transcribe_err.is_none() {
2020-11-26 15:04:23 +00:00
return ExpandResult::ok(value);
2020-03-15 13:37:30 +00:00
}
}
2021-02-01 20:42:37 +00:00
// Use the rule if we matched more tokens, or bound variables count
2020-03-15 13:37:30 +00:00
if let Some((prev_match, _)) = &match_ {
2021-02-01 20:42:37 +00:00
if (new_match.unmatched_tts, -(new_match.bound_count as i32))
< (prev_match.unmatched_tts, -(prev_match.bound_count as i32))
2020-03-15 13:37:30 +00:00
{
match_ = Some((new_match, rule));
}
} else {
match_ = Some((new_match, rule));
}
}
2020-03-15 13:37:30 +00:00
if let Some((match_, rule)) = match_ {
// if we got here, there was no match without errors
2020-11-26 15:04:23 +00:00
let ExpandResult { value, err: transcribe_err } =
2020-03-16 11:22:10 +00:00
transcriber::transcribe(&rule.rhs, &match_.bindings);
2020-11-26 15:04:23 +00:00
ExpandResult { value, err: match_.err.or(transcribe_err) }
2020-03-15 13:37:30 +00:00
} else {
2020-11-26 15:04:23 +00:00
ExpandResult::only_err(ExpandError::NoMatchingRule)
2020-03-15 13:37:30 +00:00
}
2019-01-31 10:59:25 +00:00
}
2019-01-31 20:01:34 +00:00
/// The actual algorithm for expansion is not too hard, but is pretty tricky.
/// `Bindings` structure is the key to understanding what we are doing here.
///
/// On the high level, it stores mapping from meta variables to the bits of
/// syntax it should be substituted with. For example, if `$e:expr` is matched
/// with `1 + 1` by macro_rules, the `Binding` will store `$e -> 1 + 1`.
///
/// The tricky bit is dealing with repetitions (`$()*`). Consider this example:
///
2019-02-08 10:55:45 +00:00
/// ```not_rust
2019-01-31 20:01:34 +00:00
/// macro_rules! foo {
/// ($($ i:ident $($ e:expr),*);*) => {
/// $(fn $ i() { $($ e);*; })*
/// }
/// }
/// foo! { foo 1,2,3; bar 4,5,6 }
/// ```
///
/// Here, the `$i` meta variable is matched first with `foo` and then with
/// `bar`, and `$e` is matched in turn with `1`, `2`, `3`, `4`, `5`, `6`.
///
/// To represent such "multi-mappings", we use a recursive structures: we map
/// variables not to values, but to *lists* of values or other lists (that is,
/// to the trees).
///
/// For the above example, the bindings would store
///
2019-02-08 10:55:45 +00:00
/// ```not_rust
2019-01-31 20:01:34 +00:00
/// i -> [foo, bar]
/// e -> [[1, 2, 3], [4, 5, 6]]
/// ```
///
/// We construct `Bindings` in the `match_lhs`. The interesting case is
/// `TokenTree::Repeat`, where we use `push_nested` to create the desired
/// nesting structure.
///
/// The other side of the puzzle is `expand_subtree`, where we use the bindings
/// to substitute meta variables in the output template. When expanding, we
2019-02-11 16:18:27 +00:00
/// maintain a `nesting` stack of indices which tells us which occurrence from
2019-01-31 20:01:34 +00:00
/// the `Bindings` we should take. We push to the stack when we enter a
/// repetition.
///
/// In other words, `Bindings` is a *multi* mapping from `SmolStr` to
/// `tt::TokenTree`, where the index to select a particular `TokenTree` among
/// many is not a plain `usize`, but a `&[usize]`.
2021-02-01 20:42:37 +00:00
#[derive(Debug, Default, Clone, PartialEq, Eq)]
2019-01-31 10:59:25 +00:00
struct Bindings {
inner: FxHashMap<SmolStr, Binding>,
2019-01-31 10:59:25 +00:00
}
2021-02-01 20:42:37 +00:00
#[derive(Debug, Clone, PartialEq, Eq)]
2019-01-31 12:22:55 +00:00
enum Binding {
2019-09-10 17:09:43 +00:00
Fragment(Fragment),
2019-01-31 12:22:55 +00:00
Nested(Vec<Binding>),
Empty,
2019-01-31 12:22:55 +00:00
}
2021-02-01 20:42:37 +00:00
#[derive(Debug, Clone, PartialEq, Eq)]
2019-09-10 17:09:43 +00:00
enum Fragment {
/// token fragments are just copy-pasted into the output
Tokens(tt::TokenTree),
/// Ast fragments are inserted with fake delimiters, so as to make things
/// like `$i * 2` where `$i = 1 + 1` work as expectd.
Ast(tt::TokenTree),
}
2019-03-03 19:33:50 +00:00
#[cfg(test)]
mod tests {
2020-08-12 16:26:51 +00:00
use syntax::{ast, AstNode};
2019-03-03 19:33:50 +00:00
use super::*;
use crate::syntax_node_to_token_tree;
2019-03-03 19:33:50 +00:00
#[test]
fn test_expand_rule() {
assert_err(
"($($i:ident);*) => ($i)",
"foo!{a}",
ExpandError::BindingError(String::from(
"expected simple binding, found nested binding `i`",
)),
);
2019-04-18 02:21:36 +00:00
// FIXME:
// Add an err test case for ($($i:ident)) => ($())
2019-03-03 19:33:50 +00:00
}
fn assert_err(macro_body: &str, invocation: &str, err: ExpandError) {
2020-11-26 15:04:23 +00:00
assert_eq!(
expand_first(&create_rules(&format_macro(macro_body)), invocation).err,
Some(err)
);
2019-03-03 19:33:50 +00:00
}
fn format_macro(macro_body: &str) -> String {
format!(
"
macro_rules! foo {{
{}
}}
",
macro_body
)
}
fn create_rules(macro_definition: &str) -> crate::MacroRules {
2019-05-28 14:39:01 +00:00
let source_file = ast::SourceFile::parse(macro_definition).ok().unwrap();
2019-03-03 19:33:50 +00:00
let macro_definition =
2020-12-15 14:37:37 +00:00
source_file.syntax().descendants().find_map(ast::MacroRules::cast).unwrap();
2019-03-03 19:33:50 +00:00
let (definition_tt, _) =
syntax_node_to_token_tree(macro_definition.token_tree().unwrap().syntax());
2019-03-03 19:33:50 +00:00
crate::MacroRules::parse(&definition_tt).unwrap()
}
2020-03-14 19:24:18 +00:00
fn expand_first(rules: &crate::MacroRules, invocation: &str) -> ExpandResult<tt::Subtree> {
2019-05-28 14:39:01 +00:00
let source_file = ast::SourceFile::parse(invocation).ok().unwrap();
2019-03-03 19:33:50 +00:00
let macro_invocation =
source_file.syntax().descendants().find_map(ast::MacroCall::cast).unwrap();
let (invocation_tt, _) =
syntax_node_to_token_tree(macro_invocation.token_tree().unwrap().syntax());
2019-03-03 19:33:50 +00:00
2020-03-16 17:46:08 +00:00
expand_rules(&rules.rules, &invocation_tt)
2019-03-03 19:33:50 +00:00
}
}