use super::{Token, OP_ANY, OP_LITERAL, OP_MATCH, OP_STAR_ANY, OP_STAR_LITERAL};
use crate::ops::string_matching::search_contract::MatchError;
pub fn parse_program(program: &[u8]) -> Result<Vec<Token>, MatchError> {
let mut tokens = Vec::new();
let mut index = 0usize;
while index < program.len() {
match program[index] {
OP_LITERAL => {
let byte = *program.get(index + 1).ok_or_else(|| {
"Fix: literal opcode 1 must be followed by one byte".to_string()
})?;
tokens.push(Token::Literal(byte));
index += 2;
}
OP_ANY => {
tokens.push(Token::Any);
index += 1;
}
OP_STAR_LITERAL => {
let byte = *program.get(index + 1).ok_or_else(|| {
"Fix: star-literal opcode 3 must be followed by one byte".to_string()
})?;
tokens.push(Token::StarLiteral(byte));
index += 2;
}
OP_STAR_ANY => {
tokens.push(Token::StarAny);
index += 1;
}
OP_MATCH => return Ok(tokens),
opcode => {
return Err(format!(
"Fix: replace unsupported NFA opcode {opcode} at byte offset {index}"
));
}
}
}
Err("Fix: terminate nfa_program with accept opcode 255".to_string())
}