Refactor and rename

This commit is contained in:
Edwin Cheng 2019-11-05 01:01:05 +08:00
parent 42661a3b27
commit 188a1412b9

View file

@ -52,23 +52,21 @@ pub(crate) struct Rule {
pub(crate) rhs: tt::Subtree, pub(crate) rhs: tt::Subtree,
} }
/// Find the "shift" (the highest id of the TokenId) inside a subtree // Find the max token id inside a subtree
fn find_subtree_shift(tt: &tt::Subtree, mut cur: u32) -> u32 { fn max_id(subtree: &tt::Subtree) -> Option<u32> {
use std::cmp::max; subtree
.token_trees
for t in &tt.token_trees { .iter()
cur = match t { .filter_map(|tt| match tt {
tt::TokenTree::Leaf(leaf) => match leaf { tt::TokenTree::Subtree(subtree) => max_id(subtree),
tt::Leaf::Ident(ident) if ident.id != tt::TokenId::unspecified() => { tt::TokenTree::Leaf(tt::Leaf::Ident(ident))
max(cur, ident.id.0) if ident.id != tt::TokenId::unspecified() =>
} {
_ => cur, Some(ident.id.0)
}, }
tt::TokenTree::Subtree(tt) => find_subtree_shift(tt, cur), _ => None,
} })
} .max()
cur
} }
/// Shift given TokenTree token id /// Shift given TokenTree token id
@ -77,9 +75,7 @@ fn shift_subtree(tt: &mut tt::Subtree, shift: u32) {
match t { match t {
tt::TokenTree::Leaf(leaf) => match leaf { tt::TokenTree::Leaf(leaf) => match leaf {
tt::Leaf::Ident(ident) if ident.id != tt::TokenId::unspecified() => { tt::Leaf::Ident(ident) if ident.id != tt::TokenId::unspecified() => {
// Note that TokenId is started from zero, ident.id.0 += shift;
// We have to add 1 to prevent duplication.
ident.id.0 += shift + 1;
} }
_ => (), _ => (),
}, },
@ -110,7 +106,10 @@ impl MacroRules {
validate(&rule.lhs)?; validate(&rule.lhs)?;
} }
Ok(MacroRules { rules, shift: find_subtree_shift(tt, 0) }) // Note that TokenId is started from zero,
// We have to add 1 to prevent duplication.
let shift = max_id(tt).unwrap_or(0) + 1;
Ok(MacroRules { rules, shift })
} }
pub fn expand(&self, tt: &tt::Subtree) -> Result<tt::Subtree, ExpandError> { pub fn expand(&self, tt: &tt::Subtree) -> Result<tt::Subtree, ExpandError> {