76 lines
1.8 KiB
Rust
76 lines
1.8 KiB
Rust
use std::fmt;
|
|
|
|
use crate::util::intersperse_option;
|
|
|
|
#[derive(Debug)]
|
|
pub struct Representation {
|
|
production_output: EBNF,
|
|
}
|
|
|
|
impl Representation {
|
|
pub fn show(&self) -> String {
|
|
self.production_output.to_string()
|
|
}
|
|
|
|
pub fn new() -> Self {
|
|
Self {
|
|
production_output: EBNF::None,
|
|
}
|
|
}
|
|
|
|
pub fn with_production(production_output: EBNF) -> Self {
|
|
Self { production_output }
|
|
}
|
|
}
|
|
|
|
#[derive(Debug)]
|
|
pub enum EBNF {
|
|
None,
|
|
Nonterminal(String),
|
|
CharTerminal(char),
|
|
Alternation(Vec<EBNF>),
|
|
}
|
|
|
|
impl fmt::Display for EBNF {
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
match self {
|
|
EBNF::None => write!(f, "none"),
|
|
EBNF::CharTerminal(ch) => write!(f, "'{ch}'"),
|
|
EBNF::Alternation(items) => {
|
|
for item in intersperse_option(items.iter()) {
|
|
match item {
|
|
None => write!(f, " | ")?,
|
|
Some(item) => write!(f, "{item}")?,
|
|
}
|
|
}
|
|
write!(f, "")
|
|
}
|
|
EBNF::Nonterminal(name) => write!(f, "{name}"),
|
|
}
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn test_ebnf_print() {
|
|
let example = EBNF::Alternation(vec![
|
|
EBNF::CharTerminal('f'),
|
|
EBNF::CharTerminal('a'),
|
|
EBNF::CharTerminal('k'),
|
|
EBNF::CharTerminal('e'),
|
|
]);
|
|
|
|
assert_eq!(example.to_string(), "'f' | 'a' | 'k' | 'e'");
|
|
|
|
let example = EBNF::Alternation(vec![
|
|
EBNF::Nonterminal("other-rule".into()),
|
|
EBNF::CharTerminal('q'),
|
|
EBNF::CharTerminal('m'),
|
|
]);
|
|
assert_eq!(example.to_string(), "other-rule | 'q' | 'm'");
|
|
}
|
|
}
|