Changeset - 7e640b0cffa7
[Not reviewed]
default
0 6 0
Laman - 10 months ago 2024-06-18 16:21:22

handling unparsable patterns
6 files changed with 112 insertions and 30 deletions:
0 comments (0 inline, 0 general)
regexp.py
Show inline comments
 
from abc import abstractmethod
 

	
 

	
 
class ParsingError(Exception):
 
	pass
 

	
 

	
 
class Token:
 
	is_skippable = False
 

	
 
	@abstractmethod
 
	def list_first(self):
 
		pass
 

	
 
	@abstractmethod
 
	def list_last(self):
 
		pass
 

	
 
	@abstractmethod
 
@@ -102,46 +106,54 @@ class Chain(Token):
 

	
 
def find_closing_parenthesis(pattern, k):
 
	counter = 0
 

	
 
	for (i, c) in enumerate(pattern[k:]):
 
		if c == "(":
 
			counter += 1
 
		elif c == ")":
 
			counter -= 1
 
		if counter == 0:
 
			return k+i
 

	
 
	return None
 
	raise ParsingError(f'A closing parenthesis not found. Pattern: "{pattern}", position: {k}')
 

	
 

	
 
def parse(pattern, offset=0):
 
	res = []
 

	
 
	i = 0
 
	while i < len(pattern):
 
		c = pattern[i]
 
		if c == "(":
 
			j = find_closing_parenthesis(pattern, i)
 
			inner_content = parse(pattern[i+1:j], offset+i+1)
 
			res.append(inner_content)
 
			i = j+1
 
		elif c == "*":
 
			token = res.pop()
 
			try:
 
				token = res.pop()
 
			except IndexError as e:
 
				raise ParsingError(f'The asterisk operator is missing an argument. Pattern: "{pattern}", position {i}')
 
			res.append(Asterisk(token))
 
			i += 1
 
		elif c == "+":
 
			token = res.pop()
 
			try:
 
				token = res.pop()
 
			except IndexError as e:
 
				raise ParsingError(f'The plus operator is missing an argument. Pattern: "{pattern}", position {i}')
 
			res.append(Plus(token))
 
			i += 1
 
		elif c == ")":
 
			raise ParsingError(f'An opening parenthesis not found. Pattern: "{pattern}", position: {i}')
 
		else:
 
			res.append(Symbol(i+offset, c))
 
			i += 1
 

	
 
	return Chain(res)
 

	
 

	
 
class Regexp:
 
	def __init__(self, pattern):
 
		(self.rules, self.end_states) = self._parse(pattern)
 

	
 
	def _parse(self, s):
 
@@ -219,18 +231,23 @@ class RegexpDFA:
 
		for c in s:
 
			key = (st, c)
 
			if key in self.rules:
 
				st = self.rules[key]
 
			else:
 
				return False
 

	
 
		return st in self.end_states
 

	
 

	
 
if __name__ == "__main__":
 
	tests = ["", "a", "ab", "aabb", "abab", "abcd", "abcbcdbcd"]
 
	for pattern in ["a*b*", "a+b+", "(ab)*", "(ab)+", "a((bc)*d)*"]:
 
	for pattern in ["*", "((a)", "a)"]:
 
		print("#", pattern)
 
		r = RegexpDFA(pattern)
 
		try:
 
			r = RegexpDFA(pattern)
 
		except ParsingError as e:
 
			print("Failed to parse the regexp:")
 
			print(e)
 
			continue
 
		for t in tests:
 
			print(t, r.match(t))
 
		print()
src/lib.rs
Show inline comments
 
mod regexp;
 
pub use regexp::Regexp;
 
pub use regexp::{Regexp, ParsingError};
src/main.rs
Show inline comments
 
use regexp::Regexp;
 

	
 
fn main() {
 
	let tests = ["", "a", "ab", "aabb", "abab", "abcd", "abcbcdbcd"];
 
	for pattern in ["a*b*", "a+b+", "(ab)*", "(ab)+", "a((bc)*d)*"] {
 
	for pattern in ["*", "((a)", "a)", "+a"] {
 
		println!("# {pattern}");
 
		let r = Regexp::new(&pattern.to_string()).determinize();
 
		let r = match Regexp::new(&pattern.to_string()) {
 
			Ok(r1) => r1.determinize(),
 
			Err(e) => {
 
				println!("{e}");
 
				continue;
 
			}
 
		};
 
		for &t in tests.iter() {
 
			println!("{t} {}", r.eval(t.to_string()));
 
		}
 
		println!();
 
	}
 
}
src/regexp.rs
Show inline comments
 
use std::collections::{HashMap, HashSet};
 

	
 
mod token;
 
pub use token::ParsingError;
 
use token::{Token, parse};
 

	
 
const START: usize = usize::MAX;
 

	
 
fn encode_set(set: &HashSet<usize>) -> u64 {
 
	let mut res = 0;
 
	for x in set.iter() {
 
		res ^= 1<<x;
 
	}
 
	return res;
 
}
 

	
 
@@ -19,32 +20,33 @@ fn decode_set(x: u64) ->HashSet<usize> {
 
	let mut x = x;
 
	let mut res: HashSet<usize> = HashSet::new();
 
	
 
	while x > 0 {
 
		let y = x.trailing_zeros();
 
		res.insert(y as usize);
 
		x ^= 1 << y;
 
	}
 

	
 
	return res;
 
}
 

	
 
#[derive(Debug)]
 
pub struct Regexp {
 
	rules: HashMap<(usize, char), HashSet<usize>>,
 
	end_states: HashSet<usize>
 
}
 

	
 
impl Regexp {
 
	pub fn new(pattern: &String) -> Regexp {
 
		let r = parse(pattern, 0);
 
	pub fn new(pattern: &String) -> Result<Regexp, ParsingError> {
 
		let r = parse(pattern, 0)?;
 
		let pattern_chars = Vec::from_iter(pattern.chars());
 
		let mut rules: HashMap<(usize, char), HashSet<usize>> = HashMap::new();
 
		
 
		for i in r.list_first() {
 
			let c = pattern_chars[i];
 
			let key = (START, c);
 
			match rules.get_mut(&key) {
 
				Some(set) => {set.insert(i);},
 
				None => {rules.insert(key, HashSet::from([i]));}
 
			};
 
		}
 

	
 
@@ -53,25 +55,25 @@ impl Regexp {
 
			let key = (i, c);
 
			match rules.get_mut(&key) {
 
				Some(set) => {set.insert(j);},
 
				None => {rules.insert(key, HashSet::from([j]));}
 
			};
 
		}
 

	
 
		let mut end_states = HashSet::from_iter(r.list_last().into_iter());
 
		if r.is_skippable() {
 
			end_states.insert(START);
 
		}
 

	
 
		return Regexp{rules, end_states};
 
		return Ok(Regexp{rules, end_states});
 
	}
 

	
 
	pub fn eval(&self, s: String) -> bool {
 
		let mut multistate = HashSet::from([START]);
 

	
 
		for c in s.chars() {
 
			let mut new_multistate = HashSet::new();
 

	
 
			for state in multistate {
 
				if let Some(x) = self.rules.get(&(state, c)) {
 
					new_multistate = new_multistate.union(&x).map(|&y| y).collect();
 
				} else if let Some(x) = self.rules.get(&(state, '.')) {
src/regexp/token.rs
Show inline comments
 
use std::fmt;
 

	
 
#[derive(Debug, Clone)]
 
pub enum ParsingError {
 
	Asterisk {s: String, pos: usize},
 
	Plus {s: String, pos: usize},
 
	OpeningParenthesis {s: String, pos: usize},
 
	ClosingParenthesis {s: String, pos: usize}
 
}
 

	
 
impl fmt::Display for ParsingError {
 
	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
 
		match self {
 
			ParsingError::Asterisk {s, pos} => {
 
				write!(f, "The asterisk operator is missing an argument. Pattern \"{s}\", position {pos}")
 
			},
 
			ParsingError::Plus {s, pos} => {
 
				write!(f, "The plus operator is missing an argument. Pattern \"{s}\", position {pos}")
 
			},
 
			ParsingError::OpeningParenthesis {s, pos} => {
 
				write!(f, "An opening parenthesis not found. Pattern \"{s}\", position {pos}")
 
			},
 
			ParsingError::ClosingParenthesis {s, pos} => {
 
				write!(f, "An closing parenthesis not found. Pattern \"{s}\", position {pos}")
 
			}
 
		}
 
	}
 
}
 

	
 
pub trait Token {
 
	fn is_skippable(&self) -> bool {false}
 
	fn list_first(&self) -> Vec<usize>;
 
	fn list_last(&self) -> Vec<usize>;
 
	fn list_neighbours(&self) -> Vec<(usize, usize)>;
 
}
 

	
 
pub struct Symbol {
 
	position: usize,
 
	value: char
 
}
 

	
 
@@ -135,54 +164,57 @@ fn find_closing_parenthesis(s: &String) 
 
	let chars: Vec<char> = s.chars().collect();
 
	let mut counter = 0;
 

	
 
	for (i, c) in chars.iter().enumerate() {
 
		if *c == '(' {counter += 1;}
 
		else if *c == ')' {counter -= 1;}
 
		if counter == 0 {return Some(i);}
 
	}
 

	
 
	return None;
 
}
 

	
 
pub fn parse(pattern: &String, offset: usize) -> Chain {
 
pub fn parse(pattern: &String, offset: usize) -> Result<Chain, ParsingError> {
 
	let chars: Vec<char> = pattern.chars().collect();
 
	let mut res: Vec<Box<dyn Token>> = Vec::new();
 
	let mut i = 0;
 
	while i < pattern.len() {
 
		let c = chars[i];
 
		match c {
 
			'(' => {
 
				let j = find_closing_parenthesis(&pattern[i..].to_string()).unwrap() + i;
 
				let inner_content = parse(&pattern[i+1..j].to_string(), offset+i+1);
 
				let j = find_closing_parenthesis(&pattern[i..].to_string()).ok_or(ParsingError::ClosingParenthesis {s: pattern.clone(), pos: i})? + i;
 
				let inner_content = parse(&pattern[i+1..j].to_string(), offset+i+1)?;
 
				res.push(Box::new(inner_content));
 
				i = j+1;
 
			}
 
			'*' => {
 
				let token = res.pop().unwrap();
 
				let token = res.pop().ok_or(ParsingError::Asterisk{s: pattern.clone(), pos: i})?;
 
				res.push(Box::new(Asterisk{content: token}));
 
				i += 1;
 
			}
 
			'+' => {
 
				let token = res.pop().unwrap();
 
				let token = res.pop().ok_or(ParsingError::Plus{s: pattern.clone(), pos: i})?;
 
				res.push(Box::new(Plus{content: token}));
 
				i += 1;
 
			}
 
			')' => {
 
				return Err(ParsingError::OpeningParenthesis {s: pattern.clone(), pos: i});
 
			}
 
			c => {
 
				res.push(Box::new(Symbol{position: i+offset, value: c}));
 
				i += 1;
 
			}
 
		}
 
	}
 

	
 
	return Chain{content: res};
 
	return Ok(Chain{content: res});
 
}
 

	
 
mod test {
 
	use super::*;
 

	
 
	#[test]
 
	fn test_closing_parenthesis() {
 
		let s = "()";
 
		assert_eq!(find_closing_parenthesis(&s.to_string()), Some(1));
 
	}
 
}
tests/test_regexp.rs
Show inline comments
 
use regexp::Regexp;
 
use regexp::ParsingError;
 

	
 
#[test]
 
fn test_eval_basic_nfa() {
 
	let r = Regexp::new(&String::from("abc"));
 
	let r = Regexp::new(&String::from("abc")).unwrap();
 
	assert!(r.eval(String::from("abc")));
 
	assert!(!r.eval(String::from("ab")));
 
	assert!(!r.eval(String::from("abcd")));
 
}
 

	
 
#[test]
 
fn test_eval_basic_dfa() {
 
	let r = Regexp::new(&String::from("abc")).determinize();
 
	let r = Regexp::new(&String::from("abc")).unwrap().determinize();
 
	assert!(r.eval(String::from("abc")));
 
	assert!(!r.eval(String::from("ab")));
 
	assert!(!r.eval(String::from("abcd")));
 
}
 

	
 
#[test]
 
fn test_eval_empty_nfa() {
 
	assert!(Regexp::new(&String::from("a*")).eval(String::from("")));
 
	assert!(Regexp::new(&String::from("")).eval(String::from("")));
 
	assert!(!Regexp::new(&String::from("")).eval(String::from("a")));
 
	assert!(!Regexp::new(&String::from("a")).eval(String::from("")));
 
	assert!(Regexp::new(&String::from("a*")).unwrap().eval(String::from("")));
 
	assert!(Regexp::new(&String::from("")).unwrap().eval(String::from("")));
 
	assert!(!Regexp::new(&String::from("")).unwrap().eval(String::from("a")));
 
	assert!(!Regexp::new(&String::from("a")).unwrap().eval(String::from("")));
 
}
 

	
 
#[test]
 
fn test_eval_empty_dfa() {
 
	assert!(Regexp::new(&String::from("a*")).determinize().eval(String::from("")));
 
	assert!(Regexp::new(&String::from("")).determinize().eval(String::from("")));
 
	assert!(!Regexp::new(&String::from("")).determinize().eval(String::from("a")));
 
	assert!(Regexp::new(&String::from("a*")).unwrap().determinize().eval(String::from("")));
 
	assert!(Regexp::new(&String::from("")).unwrap().determinize().eval(String::from("")));
 
	assert!(!Regexp::new(&String::from("")).unwrap().determinize().eval(String::from("a")));
 
}
 

	
 
#[test]
 
fn test_eval_asterisk_nfa() {
 
	let r = Regexp::new(&String::from("a*b*"));
 
	let r = Regexp::new(&String::from("a*b*")).unwrap();
 
	assert!(r.eval(String::from("a")));
 
	assert!(r.eval(String::from("ab")));
 
	assert!(r.eval(String::from("aabb")));
 
	assert!(!r.eval(String::from("abab")));
 
}
 

	
 
#[test]
 
fn test_eval_asterisk_dfa() {
 
	let r = Regexp::new(&String::from("a*b*")).determinize();
 
	let r = Regexp::new(&String::from("a*b*")).unwrap().determinize();
 
	assert!(r.eval(String::from("a")));
 
	assert!(r.eval(String::from("ab")));
 
	assert!(r.eval(String::from("aabb")));
 
	assert!(!r.eval(String::from("abab")));
 
}
 

	
 
#[test]
 
fn test_eval_plus_nfa() {
 
	let r = Regexp::new(&String::from("(ab)+"));
 
	let r = Regexp::new(&String::from("(ab)+")).unwrap();
 
	assert!(!r.eval(String::from("a")));
 
	assert!(r.eval(String::from("ab")));
 
	assert!(r.eval(String::from("abab")));
 
	assert!(!r.eval(String::from("aabb")));
 
}
 

	
 
#[test]
 
fn test_eval_plus_dfa() {
 
	let r = Regexp::new(&String::from("(ab)+")).determinize();
 
	let r = Regexp::new(&String::from("(ab)+")).unwrap().determinize();
 
	assert!(!r.eval(String::from("a")));
 
	assert!(r.eval(String::from("ab")));
 
	assert!(r.eval(String::from("abab")));
 
	assert!(!r.eval(String::from("aabb")));
 
}
 

	
 
#[test]
 
fn test_invalid_asterisk() {
 
	let x = Regexp::new(&String::from("*"));
 
	assert!(matches!(x, Err(ParsingError::Asterisk{s: _, pos: 0})));
 
}
 

	
 
#[test]
 
fn test_invalid_plus() {
 
	let x = Regexp::new(&String::from("+"));
 
	assert!(matches!(x, Err(ParsingError::Plus{s: _, pos: 0})));
 
}
 

	
 
#[test]
 
fn test_invalid_closing_parenthesis() {
 
	let x = Regexp::new(&String::from("(a"));
 
	assert!(matches!(x, Err(ParsingError::ClosingParenthesis{s: _, pos: 0})));
 
}
 

	
 
#[test]
 
fn test_invalid_opening_parenthesis() {
 
	let x = Regexp::new(&String::from("a)"));
 
	assert!(matches!(x, Err(ParsingError::OpeningParenthesis{s: _, pos: 1})));
 
}
0 comments (0 inline, 0 general)