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

327 lines
10 KiB
Rust
Raw Normal View History

//! `mbe` (short for Macro By Example) crate contains code for handling
2020-08-12 14:46:20 +00:00
//! `macro_rules` macros. It uses `TokenTree` (from `tt` package) as the
//! interface, although it contains some code to bridge `SyntaxNode`s and
//! `TokenTree`s as well!
2019-01-31 18:29:04 +00:00
mod parser;
2019-01-31 18:09:43 +00:00
mod mbe_expander;
2019-01-31 18:29:04 +00:00
mod syntax_bridge;
mod tt_iter;
2019-04-07 13:42:53 +00:00
mod subtree_source;
2019-01-30 20:17:32 +00:00
2020-07-11 12:57:07 +00:00
#[cfg(test)]
mod tests;
use std::fmt;
2020-12-29 18:35:21 +00:00
pub use tt::{Delimiter, DelimiterKind, Punct};
2019-01-30 20:25:02 +00:00
use crate::{
2020-12-29 18:35:21 +00:00
parser::{parse_pattern, parse_template, Op},
tt_iter::TtIter,
};
2019-03-02 19:20:26 +00:00
#[derive(Debug, PartialEq, Eq)]
2019-03-03 09:40:03 +00:00
pub enum ParseError {
2019-03-03 11:45:30 +00:00
Expected(String),
RepetitionEmtpyTokenTree,
2019-03-03 09:40:03 +00:00
}
2020-05-14 09:57:37 +00:00
#[derive(Debug, PartialEq, Eq, Clone)]
2019-03-03 09:40:03 +00:00
pub enum ExpandError {
2019-03-02 19:20:26 +00:00
NoMatchingRule,
UnexpectedToken,
BindingError(String),
ConversionError,
InvalidRepeat,
2020-03-26 16:41:44 +00:00
ProcMacroError(tt::ExpansionError),
UnresolvedProcMacro,
Other(String),
2020-03-26 16:41:44 +00:00
}
impl From<tt::ExpansionError> for ExpandError {
fn from(it: tt::ExpansionError) -> Self {
ExpandError::ProcMacroError(it)
}
2019-03-02 19:20:26 +00:00
}
impl fmt::Display for ExpandError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ExpandError::NoMatchingRule => f.write_str("no rule matches input tokens"),
ExpandError::UnexpectedToken => f.write_str("unexpected token in input"),
ExpandError::BindingError(e) => f.write_str(e),
ExpandError::ConversionError => f.write_str("could not convert tokens"),
ExpandError::InvalidRepeat => f.write_str("invalid repeat expression"),
2020-11-26 18:56:38 +00:00
ExpandError::ProcMacroError(e) => e.fmt(f),
ExpandError::UnresolvedProcMacro => f.write_str("unresolved proc macro"),
ExpandError::Other(e) => f.write_str(e),
}
}
}
pub use crate::syntax_bridge::{
2020-03-08 16:13:04 +00:00
ast_to_token_tree, parse_to_token_tree, syntax_node_to_token_tree, token_tree_to_syntax_node,
TokenMap,
};
2019-01-31 10:46:40 +00:00
2019-02-11 16:07:49 +00:00
/// This struct contains AST for a single `macro_rules` definition. What might
2019-01-31 19:14:28 +00:00
/// be very confusing is that AST has almost exactly the same shape as
/// `tt::TokenTree`, but there's a crucial difference: in macro rules, `$ident`
/// and `$()*` have special meaning (see `Var` and `Repeat` data structures)
#[derive(Clone, Debug, PartialEq, Eq)]
2019-01-31 10:40:05 +00:00
pub struct MacroRules {
rules: Vec<Rule>,
2019-11-04 15:22:18 +00:00
/// Highest id of the token we have in TokenMap
shift: Shift,
2019-01-30 20:17:32 +00:00
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct Rule {
2020-12-29 18:35:21 +00:00
lhs: MetaTemplate,
rhs: MetaTemplate,
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct MetaTemplate {
delimiter: Option<Delimiter>,
tokens: Vec<Result<Op, ExpandError>>,
}
impl<'a> MetaTemplate {
fn iter(&self) -> impl Iterator<Item = &Result<Op, ExpandError>> {
self.tokens.iter()
}
fn delimiter_kind(&self) -> Option<DelimiterKind> {
self.delimiter.map(|it| it.kind)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Shift(u32);
impl Shift {
fn new(tt: &tt::Subtree) -> Shift {
// Note that TokenId is started from zero,
// We have to add 1 to prevent duplication.
let value = max_id(tt).map_or(0, |it| it + 1);
return Shift(value);
// Find the max token id inside a subtree
fn max_id(subtree: &tt::Subtree) -> Option<u32> {
subtree
.token_trees
.iter()
.filter_map(|tt| match tt {
tt::TokenTree::Subtree(subtree) => {
let tree_id = max_id(subtree);
match subtree.delimiter {
Some(it) if it.id != tt::TokenId::unspecified() => {
Some(tree_id.map_or(it.id.0, |t| t.max(it.id.0)))
}
_ => tree_id,
}
}
tt::TokenTree::Leaf(tt::Leaf::Ident(ident))
if ident.id != tt::TokenId::unspecified() =>
{
Some(ident.id.0)
}
_ => None,
})
.max()
}
}
/// Shift given TokenTree token id
fn shift_all(self, tt: &mut tt::Subtree) {
for t in tt.token_trees.iter_mut() {
match t {
tt::TokenTree::Leaf(leaf) => match leaf {
tt::Leaf::Ident(ident) => ident.id = self.shift(ident.id),
tt::Leaf::Punct(punct) => punct.id = self.shift(punct.id),
tt::Leaf::Literal(lit) => lit.id = self.shift(lit.id),
},
tt::TokenTree::Subtree(tt) => {
2019-12-20 20:14:30 +00:00
if let Some(it) = tt.delimiter.as_mut() {
it.id = self.shift(it.id);
};
self.shift_all(tt)
}
2019-11-04 17:01:05 +00:00
}
}
}
2019-11-04 15:22:18 +00:00
fn shift(self, id: tt::TokenId) -> tt::TokenId {
if id == tt::TokenId::unspecified() {
return id;
2019-11-04 15:22:18 +00:00
}
tt::TokenId(id.0 + self.0)
}
fn unshift(self, id: tt::TokenId) -> Option<tt::TokenId> {
id.0.checked_sub(self.0).map(tt::TokenId)
2019-11-04 15:22:18 +00:00
}
}
#[derive(Debug, Eq, PartialEq)]
pub enum Origin {
Def,
Call,
}
2019-01-31 19:14:28 +00:00
impl MacroRules {
2019-03-03 09:40:03 +00:00
pub fn parse(tt: &tt::Subtree) -> Result<MacroRules, ParseError> {
2019-09-22 20:39:29 +00:00
// Note: this parsing can be implemented using mbe machinery itself, by
// matching against `$($lhs:tt => $rhs:tt);*` pattern, but implementing
// manually seems easier.
let mut src = TtIter::new(tt);
let mut rules = Vec::new();
while src.len() > 0 {
let rule = Rule::parse(&mut src)?;
rules.push(rule);
if let Err(()) = src.expect_char(';') {
if src.len() > 0 {
2020-12-29 18:35:21 +00:00
return Err(ParseError::Expected("expected `;`".to_string()));
}
break;
}
}
2019-09-22 20:39:29 +00:00
for rule in rules.iter() {
validate(&rule.lhs)?;
}
Ok(MacroRules { rules, shift: Shift::new(tt) })
2019-01-31 19:14:28 +00:00
}
2019-11-04 15:22:18 +00:00
pub fn expand(&self, tt: &tt::Subtree) -> ExpandResult<tt::Subtree> {
2019-11-04 15:22:18 +00:00
// apply shift
let mut tt = tt.clone();
self.shift.shift_all(&mut tt);
2019-11-04 15:22:18 +00:00
mbe_expander::expand(self, &tt)
2019-01-31 19:14:28 +00:00
}
pub fn map_id_down(&self, id: tt::TokenId) -> tt::TokenId {
self.shift.shift(id)
}
pub fn map_id_up(&self, id: tt::TokenId) -> (tt::TokenId, Origin) {
match self.shift.unshift(id) {
Some(id) => (id, Origin::Call),
None => (id, Origin::Def),
}
}
2019-01-31 19:14:28 +00:00
}
impl Rule {
fn parse(src: &mut TtIter) -> Result<Rule, ParseError> {
let mut lhs = src
.expect_subtree()
.map_err(|()| ParseError::Expected("expected subtree".to_string()))?
.clone();
2019-12-13 13:53:34 +00:00
lhs.delimiter = None;
src.expect_char('=').map_err(|()| ParseError::Expected("expected `=`".to_string()))?;
src.expect_char('>').map_err(|()| ParseError::Expected("expected `>`".to_string()))?;
let mut rhs = src
.expect_subtree()
.map_err(|()| ParseError::Expected("expected subtree".to_string()))?
.clone();
2019-12-13 13:53:34 +00:00
rhs.delimiter = None;
2020-12-29 18:35:21 +00:00
let lhs = MetaTemplate { tokens: parse_pattern(&lhs), delimiter: None };
let rhs = MetaTemplate { tokens: parse_template(&rhs), delimiter: None };
Ok(crate::Rule { lhs, rhs })
}
2019-04-24 15:01:32 +00:00
}
2020-12-29 18:35:21 +00:00
fn to_parse_error(e: &ExpandError) -> ParseError {
let msg = match e {
ExpandError::InvalidRepeat => "invalid repeat".to_string(),
_ => "invalid macro definition".to_string(),
};
ParseError::Expected(msg)
}
2020-12-29 18:35:21 +00:00
fn validate(pattern: &MetaTemplate) -> Result<(), ParseError> {
for op in pattern.iter() {
let op = op.as_ref().map_err(|e| to_parse_error(&e))?;
match op {
2020-12-29 18:35:21 +00:00
Op::Subtree(subtree) => validate(&subtree)?,
Op::Repeat { subtree, separator, .. } => {
// Checks that no repetition which could match an empty token
// https://github.com/rust-lang/rust/blob/a58b1ed44f5e06976de2bdc4d7dc81c36a96934f/src/librustc_expand/mbe/macro_rules.rs#L558
if separator.is_none() {
2020-12-29 18:35:21 +00:00
if subtree.iter().all(|child_op| {
match child_op.as_ref().map_err(to_parse_error) {
Ok(Op::Var { kind, .. }) => {
// vis is optional
2020-12-29 18:35:21 +00:00
if kind.as_ref().map_or(false, |it| it == "vis") {
return true;
}
}
Ok(Op::Repeat { kind, .. }) => {
return matches!(
kind,
parser::RepeatKind::ZeroOrMore | parser::RepeatKind::ZeroOrOne
)
}
_ => {}
}
false
}) {
return Err(ParseError::RepetitionEmtpyTokenTree);
}
}
validate(subtree)?
}
_ => (),
}
}
Ok(())
2019-01-30 20:25:02 +00:00
}
2019-01-31 19:14:28 +00:00
2020-11-26 15:04:23 +00:00
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct ExpandResult<T> {
pub value: T,
pub err: Option<ExpandError>,
}
2020-03-16 11:22:10 +00:00
impl<T> ExpandResult<T> {
2020-11-26 15:04:23 +00:00
pub fn ok(value: T) -> Self {
Self { value, err: None }
2020-03-16 11:22:10 +00:00
}
2020-11-26 15:04:23 +00:00
pub fn only_err(err: ExpandError) -> Self
2020-03-16 11:22:10 +00:00
where
T: Default,
{
2020-11-26 15:04:23 +00:00
Self { value: Default::default(), err: Some(err) }
2020-03-16 11:22:10 +00:00
}
pub fn str_err(err: String) -> Self
where
T: Default,
{
Self::only_err(ExpandError::Other(err))
}
2020-03-16 11:22:10 +00:00
pub fn map<U>(self, f: impl FnOnce(T) -> U) -> ExpandResult<U> {
2020-11-26 15:04:23 +00:00
ExpandResult { value: f(self.value), err: self.err }
2020-03-16 11:22:10 +00:00
}
pub fn result(self) -> Result<T, ExpandError> {
2020-11-26 15:04:23 +00:00
self.err.map(Err).unwrap_or(Ok(self.value))
2020-03-16 11:22:10 +00:00
}
}
impl<T: Default> From<Result<T, ExpandError>> for ExpandResult<T> {
2020-11-26 15:04:23 +00:00
fn from(result: Result<T, ExpandError>) -> Self {
result.map_or_else(|e| Self::only_err(e), |it| Self::ok(it))
2020-03-16 11:22:10 +00:00
}
}