#![allow(clippy::explicit_counter_loop)]
use crate::host::{type_error, PyHost};
use fusevm::Value;
pub fn entries(h: &mut PyHost) -> Vec<(String, Value)> {
let names = [
"findall",
"sub",
"split",
"match",
"search",
"fullmatch",
"escape",
];
names
.iter()
.map(|n| {
(
(*n).to_string(),
h.alloc(crate::host::PyObj::Builtin(format!("re.{n}"))),
)
})
.collect()
}
pub fn call(h: &mut PyHost, fname: &str, args: &[Value]) -> Option<Result<Value, String>> {
Some(match fname {
"findall" => findall(h, args),
"sub" => sub(h, args),
"split" => split(h, args),
"match" => search_like(h, args, Mode::Match),
"search" => search_like(h, args, Mode::Search),
"fullmatch" => search_like(h, args, Mode::Full),
"escape" => escape(h, args),
_ => return None,
})
}
fn re_error(msg: impl std::fmt::Display) -> String {
format!("re.error: {msg}")
}
fn arg_str(h: &PyHost, v: Option<&Value>) -> Option<String> {
match v {
Some(Value::Str(s)) => Some((**s).clone()),
Some(v) => h.as_str(v),
None => None,
}
}
fn req_str(
h: &PyHost,
args: &[Value],
pos: usize,
fname: &str,
param: &str,
) -> Result<String, String> {
match arg_str(h, args.get(pos)) {
Some(s) => Ok(s),
None => Err(type_error(&format!(
"{fname}() argument '{param}' must be str"
))),
}
}
fn opt_int(h: &PyHost, args: &[Value], pos: usize) -> i64 {
match args.get(pos) {
None | Some(Value::Undef) => 0,
Some(v) => h.as_int(v).unwrap_or(0),
}
}
fn compile(pat: &str) -> Result<regex::Regex, String> {
regex::Regex::new(pat).map_err(re_error)
}
fn group_count(re: ®ex::Regex) -> usize {
re.captures_len().saturating_sub(1)
}
fn build_match_tuple(h: &mut PyHost, caps: ®ex::Captures) -> Value {
let strs: Vec<Option<String>> = (0..caps.len())
.map(|i| caps.get(i).map(|m| m.as_str().to_string()))
.collect();
let items: Vec<Value> = strs
.into_iter()
.map(|s| match s {
Some(s) => h.new_str(s),
None => Value::Undef,
})
.collect();
h.new_tuple(items)
}
fn findall(h: &mut PyHost, args: &[Value]) -> Result<Value, String> {
let pat = req_str(h, args, 0, "findall", "pattern")?;
let text = req_str(h, args, 1, "findall", "string")?;
let re = compile(&pat)?;
let ng = group_count(&re);
let mut rows: Vec<Vec<Option<String>>> = Vec::new();
for caps in re.captures_iter(&text) {
if ng == 0 {
rows.push(vec![caps.get(0).map(|m| m.as_str().to_string())]);
} else {
let row = (1..=ng)
.map(|i| caps.get(i).map(|m| m.as_str().to_string()))
.collect();
rows.push(row);
}
}
let mut out: Vec<Value> = Vec::with_capacity(rows.len());
for row in rows {
if ng <= 1 {
let s = row.into_iter().next().flatten().unwrap_or_default();
out.push(h.new_str(s));
} else {
let items: Vec<Value> = row
.into_iter()
.map(|s| h.new_str(s.unwrap_or_default()))
.collect();
let t = h.new_tuple(items);
out.push(t);
}
}
Ok(h.new_list(out))
}
fn sub(h: &mut PyHost, args: &[Value]) -> Result<Value, String> {
let pat = req_str(h, args, 0, "sub", "pattern")?;
let repl = match arg_str(h, args.get(1)) {
Some(s) => s,
None => {
return Err(type_error(
"sub() repl must be str (callable repl not supported yet)",
))
}
};
let text = req_str(h, args, 2, "sub", "string")?;
let count = opt_int(h, args, 3);
let re = compile(&pat)?;
let limit = if count <= 0 {
usize::MAX
} else {
count as usize
};
let mut out = String::new();
let mut last = 0usize;
let mut done = 0usize;
for caps in re.captures_iter(&text) {
if done >= limit {
break;
}
let m = caps.get(0).expect("group 0 present for a produced match");
out.push_str(&text[last..m.start()]);
out.push_str(&expand_repl(&repl, &caps)?);
last = m.end();
done += 1;
}
out.push_str(&text[last..]);
Ok(h.new_str(out))
}
fn expand_repl(repl: &str, caps: ®ex::Captures) -> Result<String, String> {
let chars: Vec<char> = repl.chars().collect();
let mut out = String::new();
let mut i = 0;
while i < chars.len() {
let c = chars[i];
if c != '\\' {
out.push(c);
i += 1;
continue;
}
i += 1; if i >= chars.len() {
out.push('\\');
break;
}
let n = chars[i];
match n {
'\\' => {
out.push('\\');
i += 1;
}
'n' => {
out.push('\n');
i += 1;
}
't' => {
out.push('\t');
i += 1;
}
'r' => {
out.push('\r');
i += 1;
}
'f' => {
out.push('\u{0c}');
i += 1;
}
'v' => {
out.push('\u{0b}');
i += 1;
}
'a' => {
out.push('\u{07}');
i += 1;
}
'b' => {
out.push('\u{08}');
i += 1;
}
'g' => {
i += 1; if chars.get(i) != Some(&'<') {
return Err(re_error("missing < in group name reference"));
}
i += 1; let mut name = String::new();
while i < chars.len() && chars[i] != '>' {
name.push(chars[i]);
i += 1;
}
if chars.get(i) != Some(&'>') {
return Err(re_error("missing >, unterminated name in group reference"));
}
i += 1; out.push_str(&resolve_group(caps, &name)?);
}
d if d.is_ascii_digit() => {
let mut num = String::new();
num.push(d);
i += 1;
if i < chars.len() && chars[i].is_ascii_digit() {
num.push(chars[i]);
i += 1;
}
out.push_str(&resolve_group(caps, &num)?);
}
other => {
out.push('\\');
out.push(other);
i += 1;
}
}
}
Ok(out)
}
fn resolve_group(caps: ®ex::Captures, name: &str) -> Result<String, String> {
if let Ok(idx) = name.parse::<usize>() {
if idx >= caps.len() {
return Err(re_error(format!("invalid group reference {idx}")));
}
Ok(caps.get(idx).map(|m| m.as_str()).unwrap_or("").to_string())
} else {
match caps.name(name) {
Some(m) => Ok(m.as_str().to_string()),
None => Err(re_error(format!("unknown group name {name:?}"))),
}
}
}
fn split(h: &mut PyHost, args: &[Value]) -> Result<Value, String> {
let pat = req_str(h, args, 0, "split", "pattern")?;
let text = req_str(h, args, 1, "split", "string")?;
let maxsplit = opt_int(h, args, 2);
let re = compile(&pat)?;
let ng = group_count(&re);
let limit = if maxsplit <= 0 {
usize::MAX
} else {
maxsplit as usize
};
let mut pieces: Vec<String> = Vec::new();
let mut group_rows: Vec<Vec<Option<String>>> = Vec::new();
let mut last = 0usize;
let mut done = 0usize;
for caps in re.captures_iter(&text) {
if done >= limit {
break;
}
let m = caps.get(0).expect("group 0 present for a produced match");
pieces.push(text[last..m.start()].to_string());
let row = (1..=ng)
.map(|i| caps.get(i).map(|g| g.as_str().to_string()))
.collect();
group_rows.push(row);
last = m.end();
done += 1;
}
pieces.push(text[last..].to_string());
let mut out: Vec<Value> = Vec::new();
for (idx, piece) in pieces.iter().enumerate() {
out.push(h.new_str(piece.clone()));
if let Some(row) = group_rows.get(idx) {
for g in row {
match g {
Some(s) => {
let v = h.new_str(s.clone());
out.push(v);
}
None => out.push(Value::Undef),
}
}
}
}
Ok(h.new_list(out))
}
enum Mode {
Match,
Search,
Full,
}
fn search_like(h: &mut PyHost, args: &[Value], mode: Mode) -> Result<Value, String> {
let fname = match mode {
Mode::Match => "match",
Mode::Search => "search",
Mode::Full => "fullmatch",
};
let pat = req_str(h, args, 0, fname, "pattern")?;
let text = req_str(h, args, 1, fname, "string")?;
let re = match mode {
Mode::Full => compile(&format!("\\A(?:{pat})\\z"))?,
_ => compile(&pat)?,
};
let result = match re.captures(&text) {
Some(caps) => {
let anchored_ok = match mode {
Mode::Match => caps.get(0).map(|m| m.start() == 0).unwrap_or(false),
_ => true,
};
if anchored_ok {
Some(build_match_tuple(h, &caps))
} else {
None
}
}
None => None,
};
Ok(result.unwrap_or(Value::Undef))
}
fn escape(h: &mut PyHost, args: &[Value]) -> Result<Value, String> {
let s = req_str(h, args, 0, "escape", "pattern")?;
const SPECIAL: &[char] = &[
'(', ')', '[', ']', '{', '}', '?', '*', '+', '-', '|', '^', '$', '\\', '.', '&', '~', '#',
' ', '\t', '\n', '\r', '\u{0b}', '\u{0c}',
];
let mut out = String::with_capacity(s.len());
for c in s.chars() {
if SPECIAL.contains(&c) {
out.push('\\');
}
out.push(c);
}
Ok(h.new_str(out))
}