2019-09-30 11:58:53 +03:00
|
|
|
//! `mbe` (short for Macro By Example) crate contains code for handling
|
2020-08-12 16:46:20 +02:00
|
|
|
//! `macro_rules` macros. It uses `TokenTree` (from `tt` package) as the
|
2019-09-30 11:58:53 +03:00
|
|
|
//! interface, although it contains some code to bridge `SyntaxNode`s and
|
|
|
|
//! `TokenTree`s as well!
|
2021-10-09 14:48:38 +03:00
|
|
|
//!
|
2023-10-14 11:28:23 +08:00
|
|
|
//! The tests for this functionality live in another crate:
|
2021-10-09 14:48:38 +03:00
|
|
|
//! `hir_def::macro_expansion_tests::mbe`.
|
2019-01-31 21:29:04 +03:00
|
|
|
|
2022-07-20 14:59:42 +02:00
|
|
|
#![warn(rust_2018_idioms, unused_lifetimes, semicolon_in_expressions_from_macros)]
|
|
|
|
|
2019-09-17 02:54:22 +03:00
|
|
|
mod parser;
|
2021-01-29 20:23:38 +08:00
|
|
|
mod expander;
|
2019-01-31 21:29:04 +03:00
|
|
|
mod syntax_bridge;
|
2019-09-17 02:54:22 +03:00
|
|
|
mod tt_iter;
|
2021-12-25 21:59:02 +03:00
|
|
|
mod to_parser_input;
|
2019-01-30 23:17:32 +03:00
|
|
|
|
2021-02-05 19:57:32 +08:00
|
|
|
#[cfg(test)]
|
|
|
|
mod benchmark;
|
2021-05-24 18:43:42 +02:00
|
|
|
mod token_map;
|
2021-02-05 19:57:32 +08:00
|
|
|
|
2023-05-28 19:54:36 +09:00
|
|
|
use stdx::impl_from;
|
2023-09-29 12:37:57 +02:00
|
|
|
use tt::Span;
|
2023-01-31 11:49:49 +01:00
|
|
|
|
2020-11-26 16:56:22 +01:00
|
|
|
use std::fmt;
|
|
|
|
|
2019-09-17 02:54:22 +03:00
|
|
|
use crate::{
|
2022-10-10 14:25:14 +02:00
|
|
|
parser::{MetaTemplate, MetaVarKind, Op},
|
2019-09-17 02:54:22 +03:00
|
|
|
tt_iter::TtIter,
|
|
|
|
};
|
|
|
|
|
2023-06-29 11:12:48 +02:00
|
|
|
// FIXME: we probably should re-think `token_tree_to_syntax_node` interfaces
|
2021-12-27 17:54:51 +03:00
|
|
|
pub use ::parser::TopEntryPoint;
|
2023-11-24 16:38:48 +01:00
|
|
|
pub use tt::{Delimiter, DelimiterKind, Punct, SyntaxContext};
|
2021-09-05 22:30:06 +03:00
|
|
|
|
2022-01-02 02:39:14 +01:00
|
|
|
pub use crate::{
|
|
|
|
syntax_bridge::{
|
2023-12-01 13:56:25 +01:00
|
|
|
parse_exprs_with_sep, parse_to_token_tree, parse_to_token_tree_static_span,
|
|
|
|
syntax_node_to_token_tree, syntax_node_to_token_tree_modified, token_tree_to_syntax_node,
|
|
|
|
SpanMapper,
|
2022-01-02 02:39:14 +01:00
|
|
|
},
|
2023-12-03 18:50:29 +01:00
|
|
|
token_map::SpanMap,
|
2022-01-02 02:39:14 +01:00
|
|
|
};
|
|
|
|
|
2023-11-25 15:10:31 +01:00
|
|
|
pub use crate::syntax_bridge::dummy_test_span_utils::*;
|
|
|
|
|
2021-10-09 15:23:55 +03:00
|
|
|
#[derive(Debug, PartialEq, Eq, Clone)]
|
2019-03-03 10:40:03 +01:00
|
|
|
pub enum ParseError {
|
2022-02-03 17:25:24 +01:00
|
|
|
UnexpectedToken(Box<str>),
|
|
|
|
Expected(Box<str>),
|
2021-01-30 00:21:43 +08:00
|
|
|
InvalidRepeat,
|
2021-01-08 15:42:40 +01:00
|
|
|
RepetitionEmptyTokenTree,
|
2019-03-03 10:40:03 +01:00
|
|
|
}
|
|
|
|
|
2022-02-03 17:25:24 +01:00
|
|
|
impl ParseError {
|
|
|
|
fn expected(e: &str) -> ParseError {
|
|
|
|
ParseError::Expected(e.into())
|
|
|
|
}
|
|
|
|
|
|
|
|
fn unexpected(e: &str) -> ParseError {
|
|
|
|
ParseError::UnexpectedToken(e.into())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-10-09 15:23:55 +03:00
|
|
|
impl fmt::Display for ParseError {
|
|
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
|
|
match self {
|
|
|
|
ParseError::UnexpectedToken(it) => f.write_str(it),
|
|
|
|
ParseError::Expected(it) => f.write_str(it),
|
|
|
|
ParseError::InvalidRepeat => f.write_str("invalid repeat"),
|
|
|
|
ParseError::RepetitionEmptyTokenTree => f.write_str("empty token tree in repetition"),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-04-16 16:11:59 +02:00
|
|
|
#[derive(Debug, PartialEq, Eq, Clone, Hash)]
|
2019-03-03 10:40:03 +01:00
|
|
|
pub enum ExpandError {
|
2022-02-21 19:14:06 +01:00
|
|
|
BindingError(Box<Box<str>>),
|
2023-11-17 19:07:31 +01:00
|
|
|
UnresolvedBinding(Box<Box<str>>),
|
2022-02-21 19:14:06 +01:00
|
|
|
LeftoverTokens,
|
|
|
|
ConversionError,
|
|
|
|
LimitExceeded,
|
2019-03-02 20:20:26 +01:00
|
|
|
NoMatchingRule,
|
|
|
|
UnexpectedToken,
|
2023-05-28 19:54:36 +09:00
|
|
|
CountError(CountError),
|
2022-02-03 17:25:24 +01:00
|
|
|
}
|
|
|
|
|
2023-05-28 19:54:36 +09:00
|
|
|
impl_from!(CountError for ExpandError);
|
|
|
|
|
2022-02-03 17:25:24 +01:00
|
|
|
impl ExpandError {
|
2022-02-21 19:14:06 +01:00
|
|
|
fn binding_error(e: impl Into<Box<str>>) -> ExpandError {
|
|
|
|
ExpandError::BindingError(Box::new(e.into()))
|
2022-02-03 17:25:24 +01:00
|
|
|
}
|
2020-03-27 00:41:44 +08:00
|
|
|
}
|
|
|
|
|
2020-11-26 16:56:22 +01: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),
|
2023-11-17 19:07:31 +01:00
|
|
|
ExpandError::UnresolvedBinding(binding) => {
|
|
|
|
f.write_str("could not find binding ")?;
|
|
|
|
f.write_str(binding)
|
|
|
|
}
|
2020-11-26 16:56:22 +01:00
|
|
|
ExpandError::ConversionError => f.write_str("could not convert tokens"),
|
2022-02-21 19:14:06 +01:00
|
|
|
ExpandError::LimitExceeded => f.write_str("Expand exceed limit"),
|
|
|
|
ExpandError::LeftoverTokens => f.write_str("leftover tokens"),
|
2023-05-28 19:54:36 +09:00
|
|
|
ExpandError::CountError(e) => e.fmt(f),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// FIXME: Showing these errors could be nicer.
|
|
|
|
#[derive(Debug, PartialEq, Eq, Clone, Hash)]
|
|
|
|
pub enum CountError {
|
|
|
|
OutOfBounds,
|
|
|
|
Misplaced,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl fmt::Display for CountError {
|
|
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
|
|
match self {
|
|
|
|
CountError::OutOfBounds => f.write_str("${count} out of bounds"),
|
|
|
|
CountError::Misplaced => f.write_str("${count} misplaced"),
|
2020-11-26 16:56:22 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-02-11 19:07:49 +03:00
|
|
|
/// This struct contains AST for a single `macro_rules` definition. What might
|
2019-01-31 22:14:28 +03: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)
|
2019-03-13 16:04:28 +03:00
|
|
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
2023-09-29 12:37:57 +02:00
|
|
|
pub struct DeclarativeMacro<S> {
|
|
|
|
rules: Box<[Rule<S>]>,
|
2023-04-24 22:21:37 +02:00
|
|
|
// This is used for correctly determining the behavior of the pat fragment
|
|
|
|
// FIXME: This should be tracked by hygiene of the fragment identifier!
|
|
|
|
is_2021: bool,
|
2023-07-10 16:23:29 +02:00
|
|
|
err: Option<Box<ParseError>>,
|
2021-01-26 05:15:47 +08:00
|
|
|
}
|
|
|
|
|
2019-09-17 02:54:22 +03:00
|
|
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
2023-06-29 11:12:48 +02:00
|
|
|
struct Rule<S> {
|
|
|
|
lhs: MetaTemplate<S>,
|
|
|
|
rhs: MetaTemplate<S>,
|
2020-12-30 02:35:21 +08:00
|
|
|
}
|
|
|
|
|
2023-09-29 12:37:57 +02:00
|
|
|
impl<S: Span> DeclarativeMacro<S> {
|
|
|
|
pub fn from_err(err: ParseError, is_2021: bool) -> DeclarativeMacro<S> {
|
|
|
|
DeclarativeMacro { rules: Box::default(), is_2021, err: Some(Box::new(err)) }
|
2023-07-10 16:23:29 +02:00
|
|
|
}
|
|
|
|
|
2021-10-10 21:07:43 +03:00
|
|
|
/// The old, `macro_rules! m {}` flavor.
|
2023-09-29 12:37:57 +02:00
|
|
|
pub fn parse_macro_rules(tt: &tt::Subtree<S>, is_2021: bool) -> DeclarativeMacro<S> {
|
2019-09-22 23:39:29 +03:00
|
|
|
// Note: this parsing can be implemented using mbe machinery itself, by
|
|
|
|
// matching against `$($lhs:tt => $rhs:tt);*` pattern, but implementing
|
|
|
|
// manually seems easier.
|
2019-09-17 02:54:22 +03:00
|
|
|
let mut src = TtIter::new(tt);
|
|
|
|
let mut rules = Vec::new();
|
2023-07-10 16:23:29 +02:00
|
|
|
let mut err = None;
|
|
|
|
|
2019-09-17 02:54:22 +03:00
|
|
|
while src.len() > 0 {
|
2023-07-10 16:23:29 +02:00
|
|
|
let rule = match Rule::parse(&mut src, true) {
|
|
|
|
Ok(it) => it,
|
|
|
|
Err(e) => {
|
|
|
|
err = Some(Box::new(e));
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
};
|
2019-09-17 02:54:22 +03:00
|
|
|
rules.push(rule);
|
|
|
|
if let Err(()) = src.expect_char(';') {
|
|
|
|
if src.len() > 0 {
|
2023-07-10 16:23:29 +02:00
|
|
|
err = Some(Box::new(ParseError::expected("expected `;`")));
|
2019-09-17 02:54:22 +03:00
|
|
|
}
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
2019-09-22 23:39:29 +03:00
|
|
|
|
2022-01-02 02:39:14 +01:00
|
|
|
for Rule { lhs, .. } in &rules {
|
2023-07-10 16:23:29 +02:00
|
|
|
if let Err(e) = validate(lhs) {
|
|
|
|
err = Some(Box::new(e));
|
|
|
|
break;
|
|
|
|
}
|
2019-09-22 23:39:29 +03:00
|
|
|
}
|
|
|
|
|
2023-09-29 12:37:57 +02:00
|
|
|
DeclarativeMacro { rules: rules.into_boxed_slice(), is_2021, err }
|
2021-01-26 05:15:47 +08:00
|
|
|
}
|
|
|
|
|
2021-10-10 21:07:43 +03:00
|
|
|
/// The new, unstable `macro m {}` flavor.
|
2023-09-29 12:37:57 +02:00
|
|
|
pub fn parse_macro2(tt: &tt::Subtree<S>, is_2021: bool) -> DeclarativeMacro<S> {
|
2021-01-26 05:15:47 +08:00
|
|
|
let mut src = TtIter::new(tt);
|
|
|
|
let mut rules = Vec::new();
|
2023-07-10 16:23:29 +02:00
|
|
|
let mut err = None;
|
2021-01-26 05:15:47 +08:00
|
|
|
|
2023-01-31 11:49:49 +01:00
|
|
|
if tt::DelimiterKind::Brace == tt.delimiter.kind {
|
2021-03-08 22:19:44 +02:00
|
|
|
cov_mark::hit!(parse_macro_def_rules);
|
2021-01-26 05:15:47 +08:00
|
|
|
while src.len() > 0 {
|
2023-07-10 16:23:29 +02:00
|
|
|
let rule = match Rule::parse(&mut src, true) {
|
|
|
|
Ok(it) => it,
|
|
|
|
Err(e) => {
|
|
|
|
err = Some(Box::new(e));
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
};
|
2021-01-26 05:15:47 +08:00
|
|
|
rules.push(rule);
|
2021-04-03 03:08:31 +02:00
|
|
|
if let Err(()) = src.expect_any_char(&[';', ',']) {
|
2021-01-26 05:15:47 +08:00
|
|
|
if src.len() > 0 {
|
2023-07-10 16:23:29 +02:00
|
|
|
err = Some(Box::new(ParseError::expected(
|
|
|
|
"expected `;` or `,` to delimit rules",
|
|
|
|
)));
|
2021-01-26 05:15:47 +08:00
|
|
|
}
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} else {
|
2021-03-08 22:19:44 +02:00
|
|
|
cov_mark::hit!(parse_macro_def_simple);
|
2023-07-10 16:23:29 +02:00
|
|
|
match Rule::parse(&mut src, false) {
|
|
|
|
Ok(rule) => {
|
|
|
|
if src.len() != 0 {
|
|
|
|
err = Some(Box::new(ParseError::expected("remaining tokens in macro def")));
|
|
|
|
}
|
|
|
|
rules.push(rule);
|
|
|
|
}
|
|
|
|
Err(e) => {
|
|
|
|
err = Some(Box::new(e));
|
|
|
|
}
|
2021-01-26 05:15:47 +08:00
|
|
|
}
|
|
|
|
}
|
2022-01-02 02:39:14 +01:00
|
|
|
|
|
|
|
for Rule { lhs, .. } in &rules {
|
2023-07-10 16:23:29 +02:00
|
|
|
if let Err(e) = validate(lhs) {
|
|
|
|
err = Some(Box::new(e));
|
|
|
|
break;
|
|
|
|
}
|
2021-01-26 05:15:47 +08:00
|
|
|
}
|
|
|
|
|
2023-09-29 12:37:57 +02:00
|
|
|
DeclarativeMacro { rules: rules.into_boxed_slice(), is_2021, err }
|
2019-01-31 22:14:28 +03:00
|
|
|
}
|
2019-11-05 02:09:16 +08:00
|
|
|
|
2023-07-10 16:23:29 +02:00
|
|
|
pub fn err(&self) -> Option<&ParseError> {
|
|
|
|
self.err.as_deref()
|
|
|
|
}
|
|
|
|
|
2023-11-17 19:07:31 +01:00
|
|
|
pub fn expand(
|
|
|
|
&self,
|
|
|
|
tt: &tt::Subtree<S>,
|
|
|
|
marker: impl Fn(&mut S) + Copy,
|
|
|
|
) -> ExpandResult<tt::Subtree<S>> {
|
|
|
|
expander::expand_rules(&self.rules, &tt, marker, self.is_2021)
|
2021-11-22 15:59:41 +01:00
|
|
|
}
|
2019-01-31 22:14:28 +03:00
|
|
|
}
|
|
|
|
|
2023-06-29 11:12:48 +02:00
|
|
|
impl<S: Span> Rule<S> {
|
|
|
|
fn parse(src: &mut TtIter<'_, S>, expect_arrow: bool) -> Result<Self, ParseError> {
|
2022-02-03 17:25:24 +01:00
|
|
|
let lhs = src.expect_subtree().map_err(|()| ParseError::expected("expected subtree"))?;
|
2021-01-26 05:15:47 +08:00
|
|
|
if expect_arrow {
|
2022-02-03 17:25:24 +01:00
|
|
|
src.expect_char('=').map_err(|()| ParseError::expected("expected `=`"))?;
|
|
|
|
src.expect_char('>').map_err(|()| ParseError::expected("expected `>`"))?;
|
2021-01-26 05:15:47 +08:00
|
|
|
}
|
2022-02-03 17:25:24 +01:00
|
|
|
let rhs = src.expect_subtree().map_err(|()| ParseError::expected("expected subtree"))?;
|
2020-12-30 02:35:21 +08:00
|
|
|
|
2021-10-02 20:21:23 +03:00
|
|
|
let lhs = MetaTemplate::parse_pattern(lhs)?;
|
|
|
|
let rhs = MetaTemplate::parse_template(rhs)?;
|
2020-12-30 02:35:21 +08:00
|
|
|
|
2019-09-17 02:54:22 +03:00
|
|
|
Ok(crate::Rule { lhs, rhs })
|
|
|
|
}
|
2019-04-24 23:01:32 +08:00
|
|
|
}
|
2019-05-02 23:23:14 +08:00
|
|
|
|
2023-06-29 11:12:48 +02:00
|
|
|
fn validate<S: Span>(pattern: &MetaTemplate<S>) -> Result<(), ParseError> {
|
2020-12-30 02:35:21 +08:00
|
|
|
for op in pattern.iter() {
|
2019-09-17 02:54:22 +03:00
|
|
|
match op {
|
2021-06-13 09:24:16 +05:30
|
|
|
Op::Subtree { tokens, .. } => validate(tokens)?,
|
2021-01-30 16:12:30 +08:00
|
|
|
Op::Repeat { tokens: subtree, separator, .. } => {
|
2020-04-25 23:09:20 +08:00
|
|
|
// 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
|
2022-01-02 02:39:14 +01:00
|
|
|
let lsh_is_empty_seq = separator.is_none() && subtree.iter().all(|child_op| {
|
2022-10-10 14:25:14 +02:00
|
|
|
match *child_op {
|
2022-01-02 02:39:14 +01:00
|
|
|
// vis is optional
|
2022-10-10 14:25:14 +02:00
|
|
|
Op::Var { kind: Some(kind), .. } => kind == MetaVarKind::Vis,
|
2022-01-02 02:39:14 +01:00
|
|
|
Op::Repeat {
|
|
|
|
kind: parser::RepeatKind::ZeroOrMore | parser::RepeatKind::ZeroOrOne,
|
|
|
|
..
|
|
|
|
} => true,
|
|
|
|
_ => false,
|
|
|
|
}
|
|
|
|
});
|
|
|
|
if lsh_is_empty_seq {
|
2021-06-03 12:46:56 +02:00
|
|
|
return Err(ParseError::RepetitionEmptyTokenTree);
|
2020-04-25 23:09:20 +08:00
|
|
|
}
|
2019-09-17 02:54:22 +03:00
|
|
|
validate(subtree)?
|
2019-05-02 23:23:14 +08:00
|
|
|
}
|
2019-09-17 02:54:22 +03:00
|
|
|
_ => (),
|
2019-05-02 23:23:14 +08:00
|
|
|
}
|
|
|
|
}
|
2019-09-17 02:54:22 +03:00
|
|
|
Ok(())
|
2019-01-30 23:25:02 +03:00
|
|
|
}
|
2019-01-31 22:14:28 +03:00
|
|
|
|
2022-02-21 19:14:06 +01:00
|
|
|
pub type ExpandResult<T> = ValueResult<T, ExpandError>;
|
|
|
|
|
2020-11-26 16:04:23 +01:00
|
|
|
#[derive(Debug, Clone, Eq, PartialEq)]
|
2022-02-21 19:14:06 +01:00
|
|
|
pub struct ValueResult<T, E> {
|
2020-11-26 16:04:23 +01:00
|
|
|
pub value: T,
|
2022-02-21 19:14:06 +01:00
|
|
|
pub err: Option<E>,
|
2020-11-26 16:04:23 +01:00
|
|
|
}
|
2020-03-16 12:22:10 +01:00
|
|
|
|
2022-02-21 19:14:06 +01:00
|
|
|
impl<T, E> ValueResult<T, E> {
|
2023-04-16 19:20:48 +02:00
|
|
|
pub fn new(value: T, err: E) -> Self {
|
|
|
|
Self { value, err: Some(err) }
|
2020-03-16 12:22:10 +01:00
|
|
|
}
|
|
|
|
|
2023-04-16 19:20:48 +02:00
|
|
|
pub fn ok(value: T) -> Self {
|
|
|
|
Self { value, err: None }
|
2023-01-31 11:49:49 +01:00
|
|
|
}
|
|
|
|
|
2022-02-21 19:14:06 +01:00
|
|
|
pub fn only_err(err: E) -> Self
|
2020-03-16 12:22:10 +01:00
|
|
|
where
|
|
|
|
T: Default,
|
|
|
|
{
|
2020-11-26 16:04:23 +01:00
|
|
|
Self { value: Default::default(), err: Some(err) }
|
2020-03-16 12:22:10 +01:00
|
|
|
}
|
|
|
|
|
2022-02-21 19:14:06 +01:00
|
|
|
pub fn map<U>(self, f: impl FnOnce(T) -> U) -> ValueResult<U, E> {
|
|
|
|
ValueResult { value: f(self.value), err: self.err }
|
2020-11-26 16:48:17 +01:00
|
|
|
}
|
|
|
|
|
2022-02-21 19:14:06 +01:00
|
|
|
pub fn map_err<E2>(self, f: impl FnOnce(E) -> E2) -> ValueResult<T, E2> {
|
|
|
|
ValueResult { value: self.value, err: self.err.map(f) }
|
2020-03-16 12:22:10 +01:00
|
|
|
}
|
|
|
|
|
2022-02-21 19:14:06 +01:00
|
|
|
pub fn result(self) -> Result<T, E> {
|
2021-06-07 13:59:01 +02:00
|
|
|
self.err.map_or(Ok(self.value), Err)
|
2020-03-16 12:22:10 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-02-21 19:14:06 +01:00
|
|
|
impl<T: Default, E> From<Result<T, E>> for ValueResult<T, E> {
|
|
|
|
fn from(result: Result<T, E>) -> Self {
|
2021-03-21 15:33:18 +01:00
|
|
|
result.map_or_else(Self::only_err, Self::ok)
|
2020-03-16 12:22:10 +01:00
|
|
|
}
|
|
|
|
}
|