rust/crates/ra_mbe/src/mbe_expander.rs

284 lines
9.9 KiB
Rust
Raw Normal View History

2019-02-11 10:07:49 -06:00
/// This module takes a (parsed) definition of `macro_rules` invocation, a
2019-01-31 14:01:34 -06:00
/// `tt::TokenTree` representing an argument of macro invocation, and produces a
/// `tt::TokenTree` for the result of the expansion.
2019-01-31 04:59:25 -06:00
use rustc_hash::FxHashMap;
2019-01-31 12:29:04 -06:00
use ra_syntax::SmolStr;
2019-02-11 10:28:39 -06:00
use tt::TokenId;
2019-01-31 04:59:25 -06:00
2019-03-03 03:40:03 -06:00
use crate::ExpandError;
2019-01-31 12:43:54 -06:00
use crate::tt_cursor::TtCursor;
2019-01-31 04:49:57 -06:00
2019-03-03 03:40:03 -06:00
pub(crate) fn expand(
rules: &crate::MacroRules,
input: &tt::Subtree,
) -> Result<tt::Subtree, ExpandError> {
rules.rules.iter().find_map(|it| expand_rule(it, input).ok()).ok_or(ExpandError::NoMatchingRule)
2019-01-31 04:59:25 -06:00
}
2019-03-03 03:40:03 -06:00
fn expand_rule(rule: &crate::Rule, input: &tt::Subtree) -> Result<tt::Subtree, ExpandError> {
2019-01-31 08:16:02 -06:00
let mut input = TtCursor::new(input);
let bindings = match_lhs(&rule.lhs, &mut input)?;
2019-02-03 09:06:09 -06:00
if !input.is_eof() {
2019-03-03 03:40:03 -06:00
return Err(ExpandError::UnexpectedToken);
2019-02-03 09:06:09 -06:00
}
2019-01-31 08:16:02 -06:00
expand_subtree(&rule.rhs, &bindings, &mut Vec::new())
2019-01-31 04:59:25 -06:00
}
2019-01-31 14:01:34 -06: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 04:55:45 -06:00
/// ```not_rust
2019-01-31 14:01:34 -06: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 04:55:45 -06:00
/// ```not_rust
2019-01-31 14:01:34 -06: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 10:18:27 -06:00
/// maintain a `nesting` stack of indices which tells us which occurrence from
2019-01-31 14:01:34 -06: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 an `&[usize]`.
2019-01-31 04:59:25 -06:00
#[derive(Debug, Default)]
struct Bindings {
2019-01-31 06:22:55 -06:00
inner: FxHashMap<SmolStr, Binding>,
2019-01-31 04:59:25 -06:00
}
2019-01-31 06:22:55 -06:00
#[derive(Debug)]
enum Binding {
Simple(tt::TokenTree),
Nested(Vec<Binding>),
}
2019-01-31 08:16:02 -06:00
impl Bindings {
2019-03-03 03:40:03 -06:00
fn get(&self, name: &SmolStr, nesting: &[usize]) -> Result<&tt::TokenTree, ExpandError> {
2019-03-02 13:49:13 -06:00
let mut b = self
.inner
.get(name)
2019-03-03 13:33:50 -06:00
.ok_or(ExpandError::BindingError(format!("could not find binding `{}`", name)))?;
2019-01-31 08:16:02 -06:00
for &idx in nesting.iter() {
b = match b {
Binding::Simple(_) => break,
2019-03-03 03:40:03 -06:00
Binding::Nested(bs) => bs.get(idx).ok_or(ExpandError::BindingError(format!(
2019-03-03 13:33:50 -06:00
"could not find nested binding `{}`",
2019-03-03 03:40:03 -06:00
name
)))?,
2019-01-31 08:16:02 -06:00
};
}
match b {
2019-03-02 13:20:26 -06:00
Binding::Simple(it) => Ok(it),
2019-03-03 03:40:03 -06:00
Binding::Nested(_) => Err(ExpandError::BindingError(format!(
2019-03-03 13:33:50 -06:00
"expected simple binding, found nested binding `{}`",
2019-03-02 13:49:13 -06:00
name
))),
2019-01-31 08:16:02 -06:00
}
}
2019-03-02 13:20:26 -06:00
2019-03-03 03:40:03 -06:00
fn push_nested(&mut self, nested: Bindings) -> Result<(), ExpandError> {
2019-01-31 08:16:02 -06:00
for (key, value) in nested.inner {
if !self.inner.contains_key(&key) {
self.inner.insert(key.clone(), Binding::Nested(Vec::new()));
2019-01-31 06:22:55 -06:00
}
2019-01-31 08:16:02 -06:00
match self.inner.get_mut(&key) {
Some(Binding::Nested(it)) => it.push(value),
2019-03-02 13:49:13 -06:00
_ => {
2019-03-03 03:40:03 -06:00
return Err(ExpandError::BindingError(format!(
2019-03-03 13:33:50 -06:00
"could not find binding `{}`",
2019-03-02 13:49:13 -06:00
key
2019-03-03 03:40:03 -06:00
)));
2019-03-02 13:49:13 -06:00
}
2019-01-31 08:16:02 -06:00
}
}
2019-03-02 13:20:26 -06:00
Ok(())
2019-01-31 06:22:55 -06:00
}
}
2019-03-03 03:40:03 -06:00
fn match_lhs(pattern: &crate::Subtree, input: &mut TtCursor) -> Result<Bindings, ExpandError> {
2019-01-31 06:22:55 -06:00
let mut res = Bindings::default();
for pat in pattern.token_trees.iter() {
match pat {
2019-01-31 12:43:54 -06:00
crate::TokenTree::Leaf(leaf) => match leaf {
crate::Leaf::Var(crate::Var { text, kind }) => {
2019-03-03 03:40:03 -06:00
let kind = kind.clone().ok_or(ExpandError::UnexpectedToken)?;
2019-01-31 06:22:55 -06:00
match kind.as_str() {
2019-01-31 08:16:02 -06:00
"ident" => {
2019-03-03 03:40:03 -06:00
let ident =
input.eat_ident().ok_or(ExpandError::UnexpectedToken)?.clone();
2019-01-31 08:16:02 -06:00
res.inner.insert(
text.clone(),
Binding::Simple(tt::Leaf::from(ident).into()),
);
}
2019-03-03 03:40:03 -06:00
_ => return Err(ExpandError::UnexpectedToken),
2019-01-31 06:22:55 -06:00
}
}
2019-01-31 12:43:54 -06:00
crate::Leaf::Punct(punct) => {
2019-03-03 03:40:03 -06:00
if input.eat_punct() != Some(punct) {
return Err(ExpandError::UnexpectedToken);
2019-01-31 08:16:02 -06:00
}
}
crate::Leaf::Ident(ident) => {
2019-03-03 03:40:03 -06:00
if input.eat_ident().map(|i| &i.text) != Some(&ident.text) {
return Err(ExpandError::UnexpectedToken);
}
}
2019-03-03 03:40:03 -06:00
_ => return Err(ExpandError::UnexpectedToken),
2019-01-31 06:22:55 -06:00
},
2019-02-08 05:49:43 -06:00
crate::TokenTree::Repeat(crate::Repeat { subtree, kind: _, separator }) => {
2019-03-02 13:20:26 -06:00
while let Ok(nested) = match_lhs(subtree, input) {
2019-01-31 08:16:02 -06:00
res.push_nested(nested)?;
if let Some(separator) = *separator {
if !input.is_eof() {
2019-03-03 03:40:03 -06:00
if input.eat_punct().map(|p| p.char) != Some(separator) {
return Err(ExpandError::UnexpectedToken);
}
}
2019-01-31 08:16:02 -06:00
}
}
}
2019-01-31 06:22:55 -06:00
_ => {}
}
}
2019-03-02 13:20:26 -06:00
Ok(res)
2019-01-31 04:59:25 -06:00
}
2019-01-31 08:16:02 -06:00
fn expand_subtree(
2019-01-31 12:43:54 -06:00
template: &crate::Subtree,
2019-01-31 08:16:02 -06:00
bindings: &Bindings,
nesting: &mut Vec<usize>,
2019-03-03 03:40:03 -06:00
) -> Result<tt::Subtree, ExpandError> {
2019-01-31 08:16:02 -06:00
let token_trees = template
.token_trees
.iter()
.map(|it| expand_tt(it, bindings, nesting))
2019-03-03 03:40:03 -06:00
.collect::<Result<Vec<_>, ExpandError>>()?;
2019-01-31 08:16:02 -06:00
2019-03-02 13:20:26 -06:00
Ok(tt::Subtree { token_trees, delimiter: template.delimiter })
2019-01-31 08:16:02 -06:00
}
fn expand_tt(
2019-01-31 12:43:54 -06:00
template: &crate::TokenTree,
2019-01-31 08:16:02 -06:00
bindings: &Bindings,
nesting: &mut Vec<usize>,
2019-03-03 03:40:03 -06:00
) -> Result<tt::TokenTree, ExpandError> {
2019-01-31 08:16:02 -06:00
let res: tt::TokenTree = match template {
2019-01-31 12:43:54 -06:00
crate::TokenTree::Subtree(subtree) => expand_subtree(subtree, bindings, nesting)?.into(),
crate::TokenTree::Repeat(repeat) => {
2019-01-31 08:16:02 -06:00
let mut token_trees = Vec::new();
nesting.push(0);
2019-03-02 13:20:26 -06:00
while let Ok(t) = expand_subtree(&repeat.subtree, bindings, nesting) {
2019-01-31 08:16:02 -06:00
let idx = nesting.pop().unwrap();
nesting.push(idx + 1);
token_trees.push(t.into())
}
nesting.pop().unwrap();
2019-02-08 05:49:43 -06:00
tt::Subtree { token_trees, delimiter: tt::Delimiter::None }.into()
2019-01-31 08:16:02 -06:00
}
2019-01-31 12:43:54 -06:00
crate::TokenTree::Leaf(leaf) => match leaf {
2019-02-08 05:49:43 -06:00
crate::Leaf::Ident(ident) => {
2019-02-11 10:28:39 -06:00
tt::Leaf::from(tt::Ident { text: ident.text.clone(), id: TokenId::unspecified() })
.into()
2019-02-08 05:49:43 -06:00
}
2019-01-31 12:43:54 -06:00
crate::Leaf::Punct(punct) => tt::Leaf::from(punct.clone()).into(),
crate::Leaf::Var(v) => bindings.get(&v.text, nesting)?.clone(),
2019-02-08 05:49:43 -06:00
crate::Leaf::Literal(l) => tt::Leaf::from(tt::Literal { text: l.text.clone() }).into(),
2019-01-31 08:16:02 -06:00
},
};
2019-03-02 13:20:26 -06:00
Ok(res)
2019-01-31 04:49:57 -06:00
}
2019-03-03 13:33:50 -06:00
#[cfg(test)]
mod tests {
use ra_syntax::{ast, AstNode};
use super::*;
use crate::ast_to_token_tree;
#[test]
fn test_expand_rule() {
assert_err(
"($i:ident) => ($j)",
"foo!{a}",
ExpandError::BindingError(String::from("could not find binding `j`")),
);
assert_err(
"($($i:ident);*) => ($i)",
"foo!{a}",
ExpandError::BindingError(String::from(
"expected simple binding, found nested binding `i`",
)),
);
assert_err("($i) => ($i)", "foo!{a}", ExpandError::UnexpectedToken);
assert_err("($i:) => ($i)", "foo!{a}", ExpandError::UnexpectedToken);
}
fn assert_err(macro_body: &str, invocation: &str, err: ExpandError) {
assert_eq!(expand_first(&create_rules(&format_macro(macro_body)), invocation), Err(err));
}
fn format_macro(macro_body: &str) -> String {
format!(
"
macro_rules! foo {{
{}
}}
",
macro_body
)
}
fn create_rules(macro_definition: &str) -> crate::MacroRules {
let source_file = ast::SourceFile::parse(macro_definition);
let macro_definition =
source_file.syntax().descendants().find_map(ast::MacroCall::cast).unwrap();
let (definition_tt, _) = ast_to_token_tree(macro_definition.token_tree().unwrap()).unwrap();
crate::MacroRules::parse(&definition_tt).unwrap()
}
fn expand_first(
rules: &crate::MacroRules,
invocation: &str,
) -> Result<tt::Subtree, ExpandError> {
let source_file = ast::SourceFile::parse(invocation);
let macro_invocation =
source_file.syntax().descendants().find_map(ast::MacroCall::cast).unwrap();
let (invocation_tt, _) = ast_to_token_tree(macro_invocation.token_tree().unwrap()).unwrap();
expand_rule(&rules.rules[0], &invocation_tt)
}
}