Skip to content

Commit

Permalink
Regex native function: find
Browse files Browse the repository at this point in the history
  • Loading branch information
mliezun committed Jan 17, 2024
1 parent e2cd3a4 commit e792834
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/compiler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,8 @@ impl Compiler {
|| var_name == "type".to_string()
|| var_name == "env".to_string()
|| var_name == "import".to_string()
|| var_name == "net".to_string();
|| var_name == "net".to_string()
|| var_name == "re".to_string();
}

pub fn is_global_var(&self, var_name: String) -> bool {
Expand Down
4 changes: 4 additions & 0 deletions src/interpreter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,10 @@ fn setup_global_interpreter() {
"net".to_string(),
value::Value::Native(native::Net::build()),
);
my_vm.builtins.insert(
"re".to_string(),
value::Value::Native(native::Re::build()),
);
unsafe {
GLOBAL_INTERPRETER = Some(Interpreter {
vm: my_vm,
Expand Down
42 changes: 42 additions & 0 deletions src/native.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use std::{
cell::RefCell, collections::HashMap, env, fs::canonicalize, ops::Deref, rc::Rc,
time::SystemTime,
};
use regex::Regex;

use crate::errors::ERR_EXPECTED_NUMBER;
use crate::value::{BoolValue, BytesValue, DictValue};
Expand Down Expand Up @@ -933,3 +934,44 @@ impl Net {
return net;
}
}

pub struct Re {}

impl Re {
pub fn regex_find(values: Vec<Value>) -> Result<Value, RuntimeErr> {
if values.len() != 2 {
return Err(ERR_INVALID_NUMBER_ARGUMENTS);
}
let regex_value = match values.first().unwrap() {
Value::String(s) => s,
_ => {
return Err(ERR_EXPECTED_STRING);
}
};
let string_value = match values.last().unwrap() {
Value::String(s) => s,
_ => {
return Err(ERR_EXPECTED_STRING);
}
};
let re = Regex::new(regex_value.s.as_str()).unwrap();
let result: Vec<Value> = re.find_iter(string_value.s.as_str()).map(|e| Value::String(StringValue{s:String::from(e.as_str())})).collect();
return Ok(Value::List(MutValue::new(ListValue{elements: result})));
}

pub fn build() -> NativeValue {
let mut re = NativeValue {
props: HashMap::new(),
callable: None,
bind: false,
baggage: None,
};
re.props.insert("find".to_string(), Value::Native(NativeValue{
props: HashMap::new(),
callable: Some(&Self::regex_find),
bind: false,
baggage: None,
}));
return re;
}
}

0 comments on commit e792834

Please sign in to comment.