Changeset - 9e303d5ff83e
[Not reviewed]
default
0 3 0
Laman - 11 months ago 2024-06-20 13:54:48

removed Plus, made it an alias of the Alternative op
3 files changed with 5 insertions and 81 deletions:
0 comments (0 inline, 0 general)
regexp.py
Show inline comments
 
@@ -49,13 +49,15 @@ class Symbol(Token):
 
		yield from []
 

	
 
	def __str__(self):
 
		return self.value
 

	
 

	
 
class Plus(Token):
 
class Asterisk(Token):
 
	is_skippable = True
 

	
 
	def __init__(self, content: Token):
 
		self.content = content
 

	
 
	def list_first(self):
 
		yield from self.content.list_first()
 

	
 
@@ -66,19 +68,12 @@ class Plus(Token):
 
		yield from self.content.list_neighbours()
 
		for x in self.list_last():
 
			for y in self.list_first():
 
				yield (x, y)
 

	
 
	def __str__(self):
 
		return str(self.content) + "+"
 

	
 

	
 
class Asterisk(Plus):
 
	is_skippable = True
 
	
 
	def __str__(self):
 
		return str(self.content) + "*"
 

	
 

	
 
class Alternative(Token):
 
	def __init__(self, content: list):
 
		self.variants = []
 
@@ -185,22 +180,15 @@ def parse(pattern, offset=0):
 
			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 == "+":
 
			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}')
 
		elif c == "|":
 
		elif c == "|" or c == "+":
 
			is_alternative = True
 
			res.append(AlternativeSeparator())
 
			i += 1
 
		elif c == "_":
 
			res.append(Lambda())
 
			i += 1
src/regexp/token.rs
Show inline comments
 
use std::{borrow::Borrow, 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},
 
	EmptyAlternativeVariant
 
}
 

	
 
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}")
 
			},
 
@@ -36,29 +32,24 @@ pub struct Symbol {
 
}
 

	
 
pub struct Asterisk {
 
	content: Box<Token>
 
}
 

	
 
pub struct Plus {
 
	content: Box<Token>
 
}
 

	
 
pub struct Alternative {
 
	content: Vec<Box<Token>>
 
}
 

	
 
pub struct Chain {
 
	content: Vec<Box<Token>>
 
}
 

	
 
pub enum Token {
 
	Lambda,
 
	Symbol(Symbol),
 
	Asterisk(Asterisk),
 
	Plus(Plus),
 
	Alternative(Alternative),
 
	AlternativeSeparator,
 
	Chain(Chain)
 
}
 

	
 
impl Symbol {
 
@@ -94,34 +85,12 @@ impl Asterisk {
 
		}
 

	
 
		return res;
 
	}
 
}
 

	
 
impl Plus {
 
	fn list_first(&self) -> Vec<usize> {
 
		return self.content.list_first();
 
	}
 

	
 
	fn list_last(&self) -> Vec<usize> {
 
		return self.content.list_last();
 
	}
 

	
 
	fn list_neighbours(&self) -> Vec<(usize, usize)> {
 
		let mut res = self.content.list_neighbours();
 

	
 
		for x in self.list_last() {
 
			for y in self.list_first() {
 
				res.push((x, y));
 
			}
 
		}
 

	
 
		return res;
 
	}
 
}
 

	
 
impl Alternative {
 
	fn new(content: Vec<Box<Token>>) -> Result<Alternative, ParsingError> {
 
		let mut variants: Vec<Vec<Box<Token>>> = vec![Vec::new()];
 

	
 
		content.into_iter().for_each(|x| {
 
			if matches!(x.borrow(), Token::AlternativeSeparator) {
 
@@ -226,49 +195,45 @@ impl Chain {
 
impl Token {
 
	pub fn is_skippable(&self) -> bool {
 
		match self {
 
			Token::Lambda => true,
 
			Token::Symbol(_) => false,
 
			Token::Asterisk(_) => true,
 
			Token::Plus(_) => false,
 
			Token::Alternative(t) => t.is_skippable(),
 
			Token::AlternativeSeparator => panic!(),
 
			Token::Chain(t) => t.is_skippable()
 
		}
 
	}
 

	
 
	pub fn list_first(&self) -> Vec<usize> {
 
		match self {
 
			Token::Lambda => vec![],
 
			Token::Symbol(t) => t.list_first(),
 
			Token::Asterisk(t) => t.list_first(),
 
			Token::Plus(t) => t.list_first(),
 
			Token::Alternative(t) => t.list_first(),
 
			Token::AlternativeSeparator => panic!(),
 
			Token::Chain(t) => t.list_first()
 
		}
 
	}
 

	
 
	pub fn list_last(&self) -> Vec<usize> {
 
		match self {
 
			Token::Lambda => vec![],
 
			Token::Symbol(t) => t.list_last(),
 
			Token::Asterisk(t) => t.list_last(),
 
			Token::Plus(t) => t.list_last(),
 
			Token::Alternative(t) => t.list_last(),
 
			Token::AlternativeSeparator => panic!(),
 
			Token::Chain(t) => t.list_last()
 
		}
 
	}
 

	
 
	pub fn list_neighbours(&self) -> Vec<(usize, usize)> {
 
		match self {
 
			Token::Lambda => vec![],
 
			Token::Symbol(t) => t.list_neighbours(),
 
			Token::Asterisk(t) => t.list_neighbours(),
 
			Token::Plus(t) => t.list_neighbours(),
 
			Token::Alternative(t) => t.list_neighbours(),
 
			Token::AlternativeSeparator => panic!(),
 
			Token::Chain(t) => t.list_neighbours()
 
		}
 
	}
 
}
 
@@ -302,21 +267,16 @@ pub fn parse(pattern: &String, offset: u
 
			}
 
			'*' => {
 
				let token = res.pop().ok_or(ParsingError::Asterisk{s: pattern.clone(), pos: i})?;
 
				res.push(Box::new(Token::Asterisk(Asterisk{content: token})));
 
				i += 1;
 
			}
 
			'+' => {
 
				let token = res.pop().ok_or(ParsingError::Plus{s: pattern.clone(), pos: i})?;
 
				res.push(Box::new(Token::Plus(Plus{content: token})));
 
				i += 1;
 
			}
 
			')' => {
 
				return Err(ParsingError::OpeningParenthesis {s: pattern.clone(), pos: i});
 
			}
 
			'|' => {
 
			'|' | '+' => {
 
				is_alternative = true;
 
				res.push(Box::new(Token::AlternativeSeparator));
 
				i += 1;
 
			}
 
			'_' => {
 
				res.push(Box::new(Token::Lambda));
tests/test_regexp.rs
Show inline comments
 
@@ -48,30 +48,12 @@ fn test_eval_asterisk_dfa() {
 
	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)+")).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)+")).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_eval_alternative_nfa() {
 
	let r = Regexp::new(&String::from("a|b|c")).unwrap();
 
	assert!(r.eval(String::from("a")));
 
	assert!(r.eval(String::from("b")));
 
	assert!(r.eval(String::from("c")));
 
	assert!(!r.eval(String::from("")));
 
@@ -118,18 +100,12 @@ fn test_eval_lambda_dfa() {
 
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]
0 comments (0 inline, 0 general)