95 lines
2.4 KiB
Rust
95 lines
2.4 KiB
Rust
|
extern crate serde;
|
||
|
extern crate serde_json;
|
||
|
extern crate serde_yaml;
|
||
|
use serde::{Deserialize, Serialize};
|
||
|
|
||
|
mod regex_wrapper;
|
||
|
use regex_wrapper::Regex;
|
||
|
|
||
|
/// Representation of a rule in LangEvolveRs
|
||
|
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||
|
pub struct Rule {
|
||
|
/// Regex that should match the input text
|
||
|
from: Regex,
|
||
|
/// Text to replace matched text
|
||
|
to: String,
|
||
|
}
|
||
|
|
||
|
impl Rule {
|
||
|
/// Create new rule
|
||
|
///
|
||
|
/// # Arguments
|
||
|
///
|
||
|
/// * `from` - literal string that represents the regex that should match
|
||
|
/// the input text
|
||
|
/// * `to` - literal string that represents the regex text that should
|
||
|
/// replaced the text matched by `from`
|
||
|
pub fn new(from: &str, to: &str) -> Self {
|
||
|
Rule {
|
||
|
from: Regex::new(from),
|
||
|
to: String::from(to),
|
||
|
}
|
||
|
}
|
||
|
|
||
|
// TODO break categories in different rules
|
||
|
pub fn update(
|
||
|
&self,
|
||
|
categories: &std::collections::HashMap<String, String>,
|
||
|
) -> std::result::Result<Rule, String> {
|
||
|
let mut rule = self.clone();
|
||
|
let re = Regex::new("%\\D");
|
||
|
let from_match = re.is_match(&self.from.as_str());
|
||
|
let to_match = re.is_match(&self.to.as_str());
|
||
|
if from_match && !to_match {
|
||
|
for (category, content) in categories {
|
||
|
rule.from = Regex::new(
|
||
|
rule.from
|
||
|
.to_string()
|
||
|
.replace(
|
||
|
format!("%{}", category).as_str(),
|
||
|
format!("[{}]", content).as_str(),
|
||
|
)
|
||
|
.as_str(),
|
||
|
);
|
||
|
}
|
||
|
}
|
||
|
Ok(rule)
|
||
|
}
|
||
|
|
||
|
pub fn get_from(&self) -> &Regex {
|
||
|
&self.from
|
||
|
}
|
||
|
|
||
|
pub fn get_to(&self) -> String {
|
||
|
self.to.clone()
|
||
|
}
|
||
|
}
|
||
|
|
||
|
impl From<String> for Rule {
|
||
|
fn from(source: String) -> Self {
|
||
|
let components: Vec<&str> = source.split_terminator(">").collect();
|
||
|
Self {
|
||
|
from: Regex::new(components[0]),
|
||
|
to: String::from(components[1]),
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
impl PartialEq for Rule {
|
||
|
fn eq(&self, other: &Self) -> bool {
|
||
|
self.from == other.from && self.to == other.to
|
||
|
}
|
||
|
}
|
||
|
|
||
|
impl Eq for Rule {}
|
||
|
|
||
|
#[test]
|
||
|
fn rule_new() {
|
||
|
let rule1 = Rule::new("([ae]+)i", "${1}i");
|
||
|
let rule2 = Rule {
|
||
|
from: Regex::new("([ae]+)i"),
|
||
|
to: String::from("${1}i"),
|
||
|
};
|
||
|
assert_eq!(rule1, rule2);
|
||
|
}
|