Skip to content

Commit 48e0a8b

Browse files
Implement core::fmt::Display for OptimizedExpr (#889)
1 parent 597e09b commit 48e0a8b

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

meta/src/optimizer/mod.rs

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -263,6 +263,73 @@ pub struct OptimizedExprTopDownIterator {
263263
right_branches: Vec<OptimizedExpr>,
264264
}
265265

266+
impl core::fmt::Display for OptimizedExpr {
267+
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
268+
match self {
269+
OptimizedExpr::Str(s) => write!(f, "\"{}\"", s),
270+
OptimizedExpr::Insens(s) => write!(f, "^\"{}\"", s),
271+
OptimizedExpr::Range(start, end) => write!(f, "('{}'..'{}')", start, end),
272+
OptimizedExpr::Ident(id) => write!(f, "{}", id),
273+
OptimizedExpr::PeekSlice(start, end) => match end {
274+
Some(end) => write!(f, "PEEK[{}..{}]", start, end),
275+
None => write!(f, "PEEK[{}..]", start),
276+
},
277+
OptimizedExpr::PosPred(expr) => write!(f, "&{}", expr.as_ref()),
278+
OptimizedExpr::NegPred(expr) => write!(f, "!{}", expr.as_ref()),
279+
OptimizedExpr::Seq(lhs, rhs) => {
280+
let mut nodes = Vec::new();
281+
nodes.push(lhs);
282+
let mut current = rhs;
283+
while let OptimizedExpr::Seq(lhs, rhs) = current.as_ref() {
284+
nodes.push(lhs);
285+
current = rhs;
286+
}
287+
nodes.push(current);
288+
let sequence = nodes
289+
.iter()
290+
.map(|node| format!("{}", node))
291+
.collect::<Vec<_>>()
292+
.join(" ~ ");
293+
write!(f, "({})", sequence)
294+
}
295+
OptimizedExpr::Choice(lhs, rhs) => {
296+
let mut nodes = Vec::new();
297+
nodes.push(lhs);
298+
let mut current = rhs;
299+
while let OptimizedExpr::Choice(lhs, rhs) = current.as_ref() {
300+
nodes.push(lhs);
301+
current = rhs;
302+
}
303+
nodes.push(current);
304+
let sequence = nodes
305+
.iter()
306+
.map(|node| format!("{}", node))
307+
.collect::<Vec<_>>()
308+
.join(" | ");
309+
write!(f, "({})", sequence)
310+
}
311+
OptimizedExpr::Opt(expr) => write!(f, "{}?", expr),
312+
OptimizedExpr::Rep(expr) => write!(f, "{}*", expr),
313+
#[cfg(feature = "grammar-extras")]
314+
OptimizedExpr::RepOnce(expr) => write!(f, "{}+", expr),
315+
OptimizedExpr::Skip(strings) => {
316+
let strings = strings
317+
.iter()
318+
.map(|s| format!("\"{}\"", s))
319+
.collect::<Vec<_>>()
320+
.join(" | ");
321+
write!(f, "(!({}) ~ ANY)*", strings)
322+
}
323+
OptimizedExpr::Push(expr) => write!(f, "PUSH[{}]", expr),
324+
#[cfg(feature = "grammar-extras")]
325+
OptimizedExpr::NodeTag(expr, tag) => {
326+
write!(f, "(#{} = {})", tag, expr)
327+
}
328+
OptimizedExpr::RestoreOnErr(expr) => core::fmt::Display::fmt(expr.as_ref(), f),
329+
}
330+
}
331+
}
332+
266333
impl OptimizedExprTopDownIterator {
267334
/// Creates a new top down iterator from an `OptimizedExpr`.
268335
pub fn new(expr: &OptimizedExpr) -> Self {

0 commit comments

Comments
 (0)