use alloc::collections::BTreeMap;
use alloc::format;
use alloc::rc::Rc;
use alloc::string::{String, ToString};
use alloc::vec;
use alloc::vec::Vec;
use core::cell::RefCell;
use crate::classes::enumerator;
use crate::runtime::{Object, Runtime, RuntimeError, RuntimeFailure, Value, put};
const STATE: &str = "regexmatchinfo state";
const STATE_CLASS: &str = "regexmatchinfo-state";
const NAMES: [&str; 8] = [
"__enum", "__get", "__item", "count", "len", "mark", "name", "pos",
];
pub(crate) fn names() -> Vec<&'static str> {
NAMES.to_vec()
}
pub(crate) fn of(
haystack: &str,
regex: &crate::regex::Regex,
found: &crate::regex::Match,
) -> Value {
let groups = regex.group_count();
let mut spans: Vec<Value> = Vec::with_capacity(groups);
let mut names: Vec<Value> = Vec::with_capacity(groups);
for group in 0..groups {
match found.span_of(group) {
Some((start, end)) => spans.push(Value::List(vec![
Value::Int(start as i64),
Value::Int((end - start) as i64),
])),
None => spans.push(Value::List(Vec::new())),
}
names.push(Value::Text(
regex.name_of(group).unwrap_or("").to_string(),
));
}
let mut state = Object {
class: STATE_CLASS.to_string(),
properties: BTreeMap::new(),
};
put(&mut state.properties, "text", Value::Text(haystack.to_string()));
put(&mut state.properties, "spans", Value::List(spans));
put(&mut state.properties, "names", Value::List(names));
put(
&mut state.properties,
"mark",
Value::Text(String::new()),
);
let mut table = BTreeMap::new();
put(
&mut table,
STATE,
Value::Object(Rc::new(RefCell::new(state))),
);
Value::Object(Rc::new(RefCell::new(Object {
class: "regexmatchinfo".to_string(),
properties: table,
})))
}
pub(crate) fn property(
name: &str,
this: &Value,
_rt: &mut Runtime,
line: u32,
) -> Option<Result<Value, RuntimeFailure>> {
match name.to_lowercase().as_str() {
"count" => Some(count(this, line)),
"mark" => Some(mark(this, line)),
"len" => Some(whole_span(this, "Len.Get", line).map(|(_, length)| Value::Int(length))),
"pos" => Some(whole_span(this, "Pos.Get", line).map(|(place, _)| Value::Int(place))),
"name" => Some(Err(crate::classes::the_arity_failure(
"regexmatchinfo",
"Name.Get",
"Too few parameters passed to function.",
line,
))),
"__enum" | "__get" | "__item" | "base" | "__class" => None,
_ if crate::classes::the_base_object_has_the_method(&name.to_lowercase()) => None,
_ => Some(
answer(this, "__Get", &Value::Text(name.to_string()), line)
.map_err(|failure| named_for(failure, "__Get")),
),
}
}
pub(crate) fn property_with_params(
name: &str,
params: &[Value],
this: &Value,
_rt: &mut Runtime,
line: u32,
) -> Option<Result<Value, RuntimeFailure>> {
let member = match name.to_lowercase().as_str() {
"len" => "Len.Get",
"pos" => "Pos.Get",
"name" => "Name.Get",
_ => return None,
};
let key = params.first()?;
Some(answer(this, member, key, line).map_err(|failure| named_for(failure, member)))
}
pub(crate) fn call(
method: &str,
this: &Value,
arguments: &[Value],
_rt: &mut Runtime,
line: u32,
) -> Option<Result<Value, RuntimeFailure>> {
let method = method.to_lowercase();
match method.as_str() {
"__enum" => Some(enumeration(this, arguments, line)),
"__get" => {
let name = arguments
.first()
.cloned()
.unwrap_or(Value::Text(String::new()));
let params = arguments.get(1);
if let Some(Value::List(items)) = params {
if !items.is_empty() {
return Some(Err(crate::classes::the_failure_with(
"Invalid usage.",
"",
line,
)));
}
}
Some(answer(this, "__Get", &name, line))
}
"len" => Some(answer(
this,
"Len.Get",
arguments.first().unwrap_or(&Value::Int(0)),
line,
)),
"pos" => Some(answer(
this,
"Pos.Get",
arguments.first().unwrap_or(&Value::Int(0)),
line,
)),
"name" => Some(answer(
this,
"Name.Get",
arguments.first().unwrap_or(&Value::Int(0)),
line,
)),
_ => None,
}
}
pub(crate) fn item(
key: &Value,
this: &Value,
_rt: &mut Runtime,
line: u32,
) -> Option<Result<Value, RuntimeFailure>> {
Some(answer(this, "__Item.Get", key, line))
}
fn answer(
this: &Value,
member: &str,
key: &Value,
line: u32,
) -> Result<Value, RuntimeFailure> {
let group = resolve(this, key, member, line)?;
match member {
"Len.Get" => Ok(Value::Int(group.1)),
"Pos.Get" => Ok(Value::Int(group.0)),
"Name.Get" => Ok(Value::Text(name_of(this, group.2))),
_ => Ok(Value::Text(text_of(this, group.2))),
}
}
fn resolve(
this: &Value,
key: &Value,
member: &str,
line: u32,
) -> Result<(i64, i64, usize), RuntimeFailure> {
let count = count_of(this, line)?;
let group = if crate::builtins::is_numeric_value(key) {
crate::builtins::token_to_int64(key) as i32 as i64
} else {
let written = key.to_text();
let mut found: Option<i64> = None;
for group in 1..=count {
if name_of(this, group as usize).eq_ignore_ascii_case(&written) {
if found.is_none() {
found = Some(group);
}
if span_of(this, group as usize)
.map(|span| span.0 != span.1)
.unwrap_or(false)
{
found = Some(group);
break;
}
}
}
match found {
Some(group) => group,
None => return Err(the_parameter_failed(member, key, line)),
}
};
if group < 0 || group > count {
return Err(the_parameter_failed(member, key, line));
}
let span = span_of(this, group as usize);
Ok((
span.map(|span| span.0 + 1).unwrap_or(0),
span.map(|span| span.1).unwrap_or(0),
group as usize,
))
}
fn whole_span(
this: &Value,
member: &str,
line: u32,
) -> Result<(i64, i64), RuntimeFailure> {
let Some(state) = state(this) else {
return Err(not_a_match(line));
};
let state = state.borrow();
let _ = member;
match spans(&state).first() {
Some(Value::List(items)) if items.len() == 2 => Ok((
items[0].to_number().unwrap_or(0.0) as i64 + 1,
items[1].to_number().unwrap_or(0.0) as i64,
)),
_ => Ok((1, 0)),
}
}
fn count(this: &Value, line: u32) -> Result<Value, RuntimeFailure> {
Ok(Value::Int(count_of(this, line)?))
}
fn mark(this: &Value, line: u32) -> Result<Value, RuntimeFailure> {
let Some(state) = state(this) else {
return Err(not_a_match(line));
};
let state = state.borrow();
Ok(state
.value_of("mark")
.unwrap_or_else(|| Value::Text(String::new())))
}
fn enumeration(
this: &Value,
_arguments: &[Value],
line: u32,
) -> Result<Value, RuntimeFailure> {
let count = count_of(this, line)?;
let mut pairs: Vec<(Value, Value)> = Vec::new();
let mut group = 0i64;
while group <= count {
let key = match name_of(this, group as usize) {
name if name.is_empty() => Value::Int(group),
name => Value::Text(name),
};
pairs.push((key, Value::Text(text_of(this, group as usize))));
group += 1;
}
Ok(enumerator::make(pairs, enumerator::Alone::TheValue))
}
fn state(this: &Value) -> Option<Rc<RefCell<Object>>> {
let Value::Object(object) = this else {
return None;
};
let state = object.borrow().value_of(STATE)?;
match state {
Value::Object(state) => Some(state),
_ => None,
}
}
fn spans(state: &Object) -> Vec<Value> {
match state.value_of("spans") {
Some(Value::List(spans)) => spans.clone(),
_ => Vec::new(),
}
}
fn count_of(this: &Value, line: u32) -> Result<i64, RuntimeFailure> {
let Some(state) = state(this) else {
return Err(not_a_match(line));
};
let state = state.borrow();
Ok(spans(&state).len().saturating_sub(1) as i64)
}
fn span_of(this: &Value, group: usize) -> Option<(i64, i64)> {
let state = state(this)?;
let state = state.borrow();
let spans = spans(&state);
match spans.get(group) {
Some(Value::List(items)) if items.len() == 2 => Some((
items[0].to_number().unwrap_or(0.0) as i64,
items[1].to_number().unwrap_or(0.0) as i64,
)),
_ => None,
}
}
fn haystack(this: &Value) -> Option<String> {
let state = state(this)?;
let state = state.borrow();
state.value_of("text").map(|value| value.to_text())
}
fn text_of(this: &Value, group: usize) -> String {
let Some(haystack) = haystack(this) else {
return String::new();
};
let Some((start, length)) = span_of(this, group) else {
return String::new();
};
let chars: Vec<char> = haystack.chars().collect();
let start = (start.max(0) as usize).min(chars.len());
let end = (start + length.max(0) as usize).min(chars.len());
chars[start..end].iter().collect()
}
fn name_of(this: &Value, group: usize) -> String {
let Some(state) = state(this) else {
return String::new();
};
let state = state.borrow();
match state.value_of("names") {
Some(Value::List(names)) => names
.get(group)
.map(|value| value.to_text())
.unwrap_or_default(),
_ => String::new(),
}
}
fn not_a_match(line: u32) -> RuntimeFailure {
RuntimeFailure::Error(RuntimeError {
message: "this value is not a RegExMatchInfo.".to_string(),
line,
})
}
fn named_for(failure: RuntimeFailure, member: &str) -> RuntimeFailure {
crate::classes::named(
failure,
&crate::classes::the_name_of("regexmatchinfo", member),
)
}
fn the_parameter_failed(member: &str, key: &Value, line: u32) -> RuntimeFailure {
crate::classes::the_failure_with(
&format!(
"Parameter #1 of {} is invalid.",
crate::classes::the_name_of("regexmatchinfo", member)
),
&key.to_text(),
line,
)
}