Skip to content

add builtin regex function #120

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Oct 15, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ webpki-roots = { version = "0.25.0", optional = true }
viuer = { version = "0.7.1", optional = true }
num_cpus = "1.16.0"
rayon = "1.8.0"
regex = "1.10.0"

[features]
audio = ["hodaun", "crossbeam-channel", "lockfree"]
Expand Down
5 changes: 5 additions & 0 deletions src/primitive/defs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1478,6 +1478,11 @@ primitive!(
/// [under][now] can be used to time a function.
/// ex: ⍜now(5&sl1)
(0, Now, Misc, "now"),
/// Parse a regex pattern on a string
///
/// Returns an array of boxed string, with one string per matching group
/// ex: regex "([a-z]+)" "hello world"
(2, Regex, Misc, "regex"),
/// The number of radians in a quarter circle
///
/// Equivalent to `divide``2``pi` or `divide``4``tau`
Expand Down
38 changes: 38 additions & 0 deletions src/primitive/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,15 @@ use std::{
sync::{
atomic::{self, AtomicUsize},
OnceLock,
Arc
},
collections::HashMap,
};

use enum_iterator::{all, Sequence};
use once_cell::sync::Lazy;
use rand::prelude::*;
use regex::Regex;

use crate::{
algorithm::{fork, loops},
Expand All @@ -36,6 +39,10 @@ use crate::{
Uiua, UiuaError, UiuaResult,
};

thread_local! {
pub static REGEX_CACHE: RefCell<HashMap<String, Regex>> = RefCell::new(HashMap::new());
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Sequence)]
pub enum PrimClass {
Stack,
Expand Down Expand Up @@ -573,6 +580,37 @@ impl Primitive {
Primitive::InvTrace => trace(env, true)?,
Primitive::Dump => dump(env)?,
Primitive::Sys(io) => io.run(env)?,
Primitive::Regex => {
let pattern = env.pop(1)?.as_string(env, "Pattern must be a string")?;
let matching = env.pop(1)?.as_string(env, "Matching target must be a string")?;

let re = REGEX_CACHE.with(|cache_ref| {
let mut cache = cache_ref.borrow_mut();
let cached_pattern = cache.get(&pattern);
if cached_pattern.is_none() {
let regex = Regex::new(&pattern);
if regex.is_ok() {
cache.insert(pattern.clone(), regex.clone().unwrap());
}
regex
} else {
Ok(cached_pattern.unwrap().clone())
}
});

if re.is_ok() {
let matches = re.unwrap().find_iter(matching.as_str())
.map(|m| Function::constant(m.as_str()).into())
.reduce(|a, b| Value::join(a, b, env).unwrap());

env.push(matches.unwrap_or(Array::<Arc<Function>>::default().into()));
} else {
return Err(env.error(format!(
"Invalid pattern: {}",
pattern
)))
}
}
}
Ok(())
}
Expand Down
6 changes: 6 additions & 0 deletions tests/units.ua
Original file line number Diff line number Diff line change
Expand Up @@ -148,3 +148,9 @@ ParseOrZero ← ⍣parse⋅⋅0
⍤∶≅, 97 -@\0 @a
⍤∶≅, 27 -@\0 @\x1b
⍤∶≅, 4096 -@\0 @\u1000

⍤. ↧⊙(≅ "hello" ⊔⊡0) ≅ "world" ⊔⊡1 . regex "([a-z]+)" "hello world"
⍤. ↧⊙(≅ "hello" ⊔⊡0) ≅ "world" ⊔⊡1 . regex "([a-z]+)" "hello world"
⍤. ≅ {} regex "([0-9]+)" "hello world"
⍤. ⍣(regex "([a-z]" "hello world") (1;)