use std::fmt::{Display, Formatter};
use crate::fixed_sym_table::SymInfoTable;
use crate::{AltId, TokenId, VarId};
use crate::lexer::PosSpan;
use crate::log::{LogMsg, Logger};
pub(crate) mod tests;
pub mod lr;
pub mod ll1;
#[derive(Clone, Copy, Default, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
pub enum Symbol {
T(TokenId), NT(VarId), #[default] Empty, End }
impl Symbol {
pub fn is_end(&self) -> bool {
matches!(self, Symbol::End)
}
pub fn is_empty(&self) -> bool {
matches!(self, Symbol::Empty)
}
pub fn is_t(&self) -> bool {
matches!(self, Symbol::T(_))
}
pub fn is_nt(&self) -> bool {
matches!(self, Symbol::NT(_))
}
pub fn is_t_or_nt(&self) -> bool {
matches!(self, Symbol::T(_) | Symbol::NT(_))
}
pub fn to_str<T: SymInfoTable>(&self, symbol_table: Option<&T>) -> String {
symbol_table.map(|t| t.get_str(self)).unwrap_or_else(|| self.to_string())
}
pub fn to_str_quote<T: SymInfoTable>(&self, symbol_table: Option<&T>) -> String {
symbol_table.map(|t| t.get_name_quote(self)).unwrap_or_else(|| self.to_string())
}
pub fn to_str_name<T: SymInfoTable>(&self, symbol_table: Option<&T>) -> String {
symbol_table.map(|t| t.get_name(self)).unwrap_or_else(|| self.to_string())
}
pub fn to_str_ext<T: SymInfoTable>(&self, symbol_table: Option<&T>, ext: &String) -> String {
let mut result = self.to_str(symbol_table);
if let Some(t) = symbol_table {
if t.is_symbol_t_data(self) {
result.push_str(&format!("({ext})"));
}
}
result
}
pub fn to_str_type<T: SymInfoTable>(&self, symbol_table: Option<&T>, ext: &String) -> String {
match self {
Symbol::T(t) => format!("input {}", terminal_to_str_type(*t, symbol_table, ext)),
Symbol::NT(_) => format!("nonterminal {}", self.to_str(symbol_table)),
Symbol::Empty => "empty symbol".to_string(),
Symbol::End => "end of stream".to_string(),
}
}
pub fn to_macro_item(&self) -> String {
match self {
Symbol::Empty => "e".to_string(),
Symbol::T(x) => format!("t {x}"),
Symbol::NT(x) => format!("nt {x}"),
Symbol::End => "end".to_string(),
}
}
}
pub fn terminal_to_str_type<T: SymInfoTable>(token: TokenId, symbol_table: Option<&T>, ext: &String) -> String {
let mut result = format!("{ext:?}");
if let Some(t) = symbol_table {
if t.is_token_data(token) {
result.push_str(&format!(" ({})", t.get_t_name(token)));
}
}
result
}
impl Display for Symbol {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Symbol::Empty => write!(f, "ε"),
Symbol::T(id) => write!(f, ":{id}"),
Symbol::NT(id) => write!(f, "{id}"),
Symbol::End => write!(f, "$"),
}
}
}
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum OpCode {
Empty, T(TokenId), NT(VarId), Loop(VarId), Exit(VarId), Hook, End, }
impl Display for OpCode {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
OpCode::Empty => write!(f, "ε"),
OpCode::T(t) => write!(f, ":{t}"),
OpCode::NT(v) => write!(f, "►{v}"),
OpCode::Loop(v) => write!(f, "●{v}"),
OpCode::Exit(v) => write!(f, "◄{v}"),
OpCode::Hook => write!(f, "▲"),
OpCode::End => write!(f, "$"),
}
}
}
impl OpCode {
pub fn is_loop(&self) -> bool {
matches!(self, OpCode::Loop(_))
}
pub fn is_empty(&self) -> bool {
matches!(self, OpCode::Empty)
}
pub fn has_span(&self) -> bool {
matches!(self, OpCode::T(_) | OpCode::NT(_))
}
pub fn matches(&self, s: Symbol) -> bool {
match self {
OpCode::Empty => s == Symbol::Empty,
OpCode::T(t) => s == Symbol::T(*t),
OpCode::NT(v) => s == Symbol::NT(*v),
OpCode::End => s == Symbol::End,
OpCode::Loop(_)
| OpCode::Exit(_)
| OpCode::Hook => false,
}
}
pub fn to_str<T: SymInfoTable>(&self, symbol_table: Option<&T>) -> String {
if let Some(t) = symbol_table {
match self {
OpCode::Empty => "ε".to_string(),
OpCode::T(v) => format!("{}{}", t.get_t_str(*v), if t.is_token_data(*v) { "!" } else { "" }),
OpCode::NT(v) => format!("►{}", t.get_nt_name(*v)),
OpCode::Loop(v) => format!("●{}", t.get_nt_name(*v)),
OpCode::Exit(f) => format!("◄{f}"),
OpCode::Hook => "▲".to_string(),
OpCode::End => "$".to_string(),
}
} else {
self.to_string()
}
}
pub fn to_str_name<T: SymInfoTable>(&self, symbol_table: Option<&T>) -> String {
if let Some(tbl) = symbol_table {
match self {
OpCode::T(v) => tbl.get_t_str(*v),
_ => self.to_str(symbol_table),
}
} else {
self.to_string()
}
}
pub fn to_str_quote<T: SymInfoTable>(&self, symbol_table: Option<&T>) -> String {
if let Some(t) = symbol_table {
match self {
OpCode::T(v) => format!("{}{}", Symbol::T(*v).to_str_quote(symbol_table), if t.is_token_data(*v) { "!" } else { "" }),
_ => self.to_str(symbol_table)
}
} else {
self.to_string()
}
}
pub fn to_str_ext<T: SymInfoTable>(&self, symbol_table: Option<&T>, ext: &String) -> String {
let mut result = self.to_str(symbol_table);
if let Some(t) = symbol_table {
if let OpCode::T(tok) = self {
if t.is_symbol_t_data(&Symbol::T(*tok)) {
result.push_str(&format!("({ext})"));
}
}
}
result
}
}
impl From<Symbol> for OpCode {
fn from(value: Symbol) -> Self {
match value {
Symbol::Empty => OpCode::Empty,
Symbol::T(t) => OpCode::T(t),
Symbol::NT(v) => OpCode::NT(v),
Symbol::End => OpCode::End,
}
}
}
impl OpCode {
pub fn to_macro_item(&self) -> String {
match self {
OpCode::Empty => "e".to_string(),
OpCode::T(t) => format!("t {t}"),
OpCode::NT(v) => format!("nt {v}"),
OpCode::Loop(v) => format!("loop {v}"),
OpCode::Exit(v) => format!("exit {v}"),
OpCode::Hook => "hook".to_string(),
OpCode::End => "end".to_string(),
}
}
}
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum Terminate {
None,
Abort,
Conclude,
}
#[derive(PartialEq, Debug)]
pub enum Call {
Enter,
Loop,
Exit,
End(Terminate)
}
#[derive(PartialEq, Debug)]
pub enum RecoveryNt {
Abort,
Skip,
Done,
}
pub trait ListenerWrapper {
#[allow(unused_variables)]
fn switch(&mut self, call: Call, nt: VarId, alt_id: AltId, t_data: Option<Vec<String>>) {}
fn check_abort_request(&self) -> Terminate { Terminate::None }
fn abort(&mut self) {}
fn get_log_mut(&mut self) -> &mut impl Logger;
#[allow(unused_variables)]
fn report(&mut self, span_opt: Option<&PosSpan>, msg: LogMsg) {
self.get_log_mut().add(msg);
}
fn is_stack_empty(&self) -> bool { true }
fn is_stack_t_empty(&self) -> bool { true }
fn is_stack_span_empty(&self) -> bool { true }
#[allow(unused_variables)]
fn hook(&mut self, token: TokenId, text: &str, span: &PosSpan) -> TokenId {
token
}
#[allow(unused_variables)]
fn intercept_token(&mut self, token: TokenId, text: &str, span: &PosSpan) -> TokenId {
token
}
fn get_status(&self) -> Vec<String> { Vec::new() }
#[allow(unused_variables)]
fn push_span(&mut self, span: PosSpan) {}
fn pop_span(&mut self) -> PosSpan { PosSpan::empty() }
}
pub type ParserToken = (TokenId, String, PosSpan);
#[derive(PartialEq, Debug)]
pub enum ParserError {
SyntaxError,
TooManyErrors,
Irrecoverable,
ExtraSymbol,
UnexpectedEOS,
UnexpectedError,
EncounteredErrors,
AbortRequest,
}
impl Display for ParserError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", match self {
ParserError::SyntaxError => "syntax error",
ParserError::TooManyErrors => "too many errors while trying to recover",
ParserError::Irrecoverable => "irrecoverable syntax error",
ParserError::ExtraSymbol => "extra symbol after end of parsing",
ParserError::UnexpectedEOS => "unexpected end of stream",
ParserError::UnexpectedError => "unexpected error",
ParserError::EncounteredErrors => "parsing failed due to previously encountered error(s)",
ParserError::AbortRequest => "abort request",
})
}
}