Skip to content

Commit

Permalink
Implement core::fmt::Display for OptimizedExpr (#889)
Browse files Browse the repository at this point in the history
  • Loading branch information
TheVeryDarkness committed Jul 16, 2023
1 parent 597e09b commit 48e0a8b
Showing 1 changed file with 67 additions and 0 deletions.
67 changes: 67 additions & 0 deletions meta/src/optimizer/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,73 @@ pub struct OptimizedExprTopDownIterator {
right_branches: Vec<OptimizedExpr>,
}

impl core::fmt::Display for OptimizedExpr {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
OptimizedExpr::Str(s) => write!(f, "\"{}\"", s),
OptimizedExpr::Insens(s) => write!(f, "^\"{}\"", s),
OptimizedExpr::Range(start, end) => write!(f, "('{}'..'{}')", start, end),
OptimizedExpr::Ident(id) => write!(f, "{}", id),
OptimizedExpr::PeekSlice(start, end) => match end {
Some(end) => write!(f, "PEEK[{}..{}]", start, end),
None => write!(f, "PEEK[{}..]", start),
},
OptimizedExpr::PosPred(expr) => write!(f, "&{}", expr.as_ref()),
OptimizedExpr::NegPred(expr) => write!(f, "!{}", expr.as_ref()),
OptimizedExpr::Seq(lhs, rhs) => {
let mut nodes = Vec::new();
nodes.push(lhs);
let mut current = rhs;
while let OptimizedExpr::Seq(lhs, rhs) = current.as_ref() {
nodes.push(lhs);
current = rhs;
}
nodes.push(current);
let sequence = nodes
.iter()
.map(|node| format!("{}", node))
.collect::<Vec<_>>()
.join(" ~ ");
write!(f, "({})", sequence)
}
OptimizedExpr::Choice(lhs, rhs) => {
let mut nodes = Vec::new();
nodes.push(lhs);
let mut current = rhs;
while let OptimizedExpr::Choice(lhs, rhs) = current.as_ref() {
nodes.push(lhs);
current = rhs;
}
nodes.push(current);
let sequence = nodes
.iter()
.map(|node| format!("{}", node))
.collect::<Vec<_>>()
.join(" | ");
write!(f, "({})", sequence)
}
OptimizedExpr::Opt(expr) => write!(f, "{}?", expr),
OptimizedExpr::Rep(expr) => write!(f, "{}*", expr),
#[cfg(feature = "grammar-extras")]
OptimizedExpr::RepOnce(expr) => write!(f, "{}+", expr),
OptimizedExpr::Skip(strings) => {
let strings = strings
.iter()
.map(|s| format!("\"{}\"", s))
.collect::<Vec<_>>()
.join(" | ");
write!(f, "(!({}) ~ ANY)*", strings)
}
OptimizedExpr::Push(expr) => write!(f, "PUSH[{}]", expr),
#[cfg(feature = "grammar-extras")]
OptimizedExpr::NodeTag(expr, tag) => {
write!(f, "(#{} = {})", tag, expr)
}
OptimizedExpr::RestoreOnErr(expr) => core::fmt::Display::fmt(expr.as_ref(), f),
}
}
}

impl OptimizedExprTopDownIterator {
/// Creates a new top down iterator from an `OptimizedExpr`.
pub fn new(expr: &OptimizedExpr) -> Self {
Expand Down

0 comments on commit 48e0a8b

Please sign in to comment.