use std::collections::HashSet;
use std::sync::Arc;
use relate_core::{
integer_args::{self, IntegerArgSite},
Error, ErrorKind, Result, Value,
};
use unicode_normalization::UnicodeNormalization;
use crate::overlay::ExecGraph;
use super::super::string::{
char_range, charge_unicode_expansion, str_unary_charged, string_arg, trim_function,
trim_spec_function, TrimMode,
};
use super::render_scalar;
pub(super) fn bi_string_interp(graph: &ExecGraph<'_>, _n: &str, vals: Vec<Value>) -> Result<Value> {
if let [Value::String(s)] = vals.as_slice() {
return Ok(Value::String(Arc::clone(s)));
}
let mut out = String::new();
let mut retained = graph.retain_bytes(0)?;
for v in &vals {
let rendered: Arc<str> = match v {
Value::Null => return Ok(Value::Null),
Value::Vector { .. } => Arc::from(v.to_display_string()),
other => {
let Some(rendered) = render_scalar(other) else {
return Err(Error::ty(
"InvalidArgumentValue: string interpolation cannot coerce value to STRING",
));
};
rendered
}
};
retained.add_allocation(graph, relate_core::str_logical_bytes(&rendered))?;
out.push_str(&rendered);
}
Ok(Value::String(out.into()))
}
pub(super) fn bi_normalize(graph: &ExecGraph<'_>, _n: &str, vals: Vec<Value>) -> Result<Value> {
Ok({
let Some(value) = vals.first() else {
return Err(Error::semantic("normalize() requires an argument"));
};
match value {
Value::Null => Value::Null,
Value::String(s) => {
charge_unicode_expansion(graph, s)?;
let form = vals.get(1).and_then(Value::as_string).unwrap_or("NFC");
let normalized: String = match form.to_ascii_uppercase().as_str() {
"NFD" => s.nfd().collect(),
"NFKC" => s.nfkc().collect(),
"NFKD" => s.nfkd().collect(),
_ => s.nfc().collect(),
};
Value::String(normalized.into())
}
_ => return Err(Error::ty("normalize() requires a string")),
}
})
}
pub(super) fn bi_char_length(_graph: &ExecGraph<'_>, _n: &str, vals: Vec<Value>) -> Result<Value> {
Ok(match vals.first() {
Some(Value::String(s)) => Value::Int(s.chars().count() as i64),
Some(Value::Null) | None => Value::Null,
_ => return Err(Error::ty("char_length() needs a string")),
})
}
pub(super) fn bi_octet_length(_graph: &ExecGraph<'_>, _n: &str, vals: Vec<Value>) -> Result<Value> {
Ok(match vals.first() {
Some(Value::String(s)) => Value::Int(s.len() as i64),
Some(Value::Null) | None => Value::Null,
_ => return Err(Error::ty("octet_length() needs a string")),
})
}
pub(super) fn bi_lower(graph: &ExecGraph<'_>, _n: &str, vals: Vec<Value>) -> Result<Value> {
str_unary_charged(graph, &vals, |s| s.to_lowercase())
}
pub(super) fn bi_upper(graph: &ExecGraph<'_>, _n: &str, vals: Vec<Value>) -> Result<Value> {
str_unary_charged(graph, &vals, |s| s.to_uppercase())
}
pub(super) fn bi_trim(_graph: &ExecGraph<'_>, _n: &str, vals: Vec<Value>) -> Result<Value> {
trim_function(&vals, TrimMode::Both, true)
}
pub(super) fn bi_trim_leading(_graph: &ExecGraph<'_>, _n: &str, vals: Vec<Value>) -> Result<Value> {
trim_function(&vals, TrimMode::Leading, true)
}
pub(super) fn bi_trim_trailing(
_graph: &ExecGraph<'_>,
_n: &str,
vals: Vec<Value>,
) -> Result<Value> {
trim_function(&vals, TrimMode::Trailing, true)
}
pub(super) fn bi_trim_spec(_graph: &ExecGraph<'_>, _n: &str, vals: Vec<Value>) -> Result<Value> {
trim_spec_function(&vals)
}
pub(super) fn bi_btrim(_graph: &ExecGraph<'_>, _n: &str, vals: Vec<Value>) -> Result<Value> {
trim_function(&vals, TrimMode::Both, false)
}
pub(super) fn bi_ltrim(_graph: &ExecGraph<'_>, _n: &str, vals: Vec<Value>) -> Result<Value> {
trim_function(&vals, TrimMode::Leading, false)
}
pub(super) fn bi_rtrim(_graph: &ExecGraph<'_>, _n: &str, vals: Vec<Value>) -> Result<Value> {
trim_function(&vals, TrimMode::Trailing, false)
}
fn replace_limit(arg: Option<&Value>) -> Result<Option<usize>> {
match arg {
None => Ok(Some(usize::MAX)),
Some(Value::Null) => Ok(None),
Some(Value::Int(value)) if *value >= 0 => usize::try_from(*value).map(Some).map_err(|_| {
Error::argument_value_kind(ErrorKind::NumberOutOfRange, "replace limit out of range")
}),
Some(Value::Int(_)) => Err(Error::argument_value_kind(
ErrorKind::NumberOutOfRange,
"replace limit must be non-negative",
)),
Some(_) => Err(Error::invalid_argument_type(
"replace limit must be INTEGER",
)),
}
}
pub(super) fn bi_replace(graph: &ExecGraph<'_>, _n: &str, vals: Vec<Value>) -> Result<Value> {
let (Some(s), Some(f), Some(t)) = (
string_arg(&vals, 0)?,
string_arg(&vals, 1)?,
string_arg(&vals, 2)?,
) else {
return Ok(Value::Null);
};
let Some(limit) = replace_limit(vals.get(3))? else {
return Ok(Value::Null);
};
let occurrences = s.matches(f).count().min(limit);
graph.charge_expression(
relate_core::str_logical_bytes(s)
.saturating_add((occurrences as u64).saturating_mul(t.len().max(f.len()) as u64)),
)?;
Ok(Value::String(s.replacen(f, t, limit).into()))
}
fn charge_split_bound(graph: &ExecGraph<'_>, source: &str, delimiter_bytes: usize) -> Result<()> {
let parts = source.len().saturating_add(1) as u64;
let delimiter_scan = (source.len() as u64).saturating_mul(delimiter_bytes as u64);
graph.charge_expression(
crate::workspace::value_buffer_bytes(source.len().saturating_add(1))
.saturating_add(parts.saturating_mul(relate_core::str_logical_bytes("")))
.saturating_add(relate_core::str_logical_bytes(source))
.saturating_add(delimiter_scan),
)
}
fn earliest_delimiter<'d>(
graph: &ExecGraph<'_>,
source: &str,
from: usize,
delimiters: &[&'d str],
) -> Result<Option<(usize, &'d str)>> {
for (index, _) in source[from..].char_indices() {
graph.cancel_tick()?;
let at = from + index;
let tail = &source[at..];
if let Some(delimiter) = delimiters
.iter()
.find(|delimiter| tail.starts_with(**delimiter))
{
return Ok(Some((at, *delimiter)));
}
}
Ok(None)
}
fn strip_delimiter(graph: &ExecGraph<'_>, source: &str, delimiter: &str) -> Result<String> {
let mut out = String::with_capacity(source.len());
let mut copied = 0;
let mut pos = 0;
while pos < source.len() {
graph.cancel_tick()?;
if source[pos..].starts_with(delimiter) {
out.push_str(&source[copied..pos]);
pos += delimiter.len();
copied = pos;
} else {
let ch = source[pos..]
.chars()
.next()
.expect("pos stays on a character boundary");
pos += ch.len_utf8();
}
}
out.push_str(&source[copied..]);
Ok(out)
}
fn split_per_code_point(graph: &ExecGraph<'_>, source: &str) -> Result<Vec<Value>> {
let mut parts = Vec::with_capacity(source.len());
for (i, ch) in source.char_indices() {
graph.cancel_tick()?;
parts.push(Value::String(source[i..i + ch.len_utf8()].into()));
}
Ok(parts)
}
enum SplitMode<'a> {
WholeInput,
PerCodePoint { strip: Vec<&'a str> },
Delimiters(Vec<&'a str>),
}
fn split_mode<'a>(source: &str, delimiters: Vec<&'a str>) -> SplitMode<'a> {
let mut seen = HashSet::with_capacity(delimiters.len());
let mut distinct = Vec::with_capacity(delimiters.len());
for delimiter in delimiters {
if seen.insert(delimiter) {
distinct.push(delimiter);
}
}
if !source.is_empty() && distinct.contains(&source) {
SplitMode::WholeInput
} else if distinct.iter().any(|delimiter| delimiter.is_empty()) {
SplitMode::PerCodePoint {
strip: distinct
.into_iter()
.filter(|delimiter| !delimiter.is_empty())
.collect(),
}
} else {
SplitMode::Delimiters(distinct)
}
}
fn split_on_delimiters(
graph: &ExecGraph<'_>,
source: &str,
mode: SplitMode<'_>,
) -> Result<Vec<Value>> {
match mode {
SplitMode::WholeInput => Ok(vec![Value::String("".into()), Value::String("".into())]),
SplitMode::PerCodePoint { strip } => {
if strip.is_empty() {
return split_per_code_point(graph, source);
}
let mut reduced = String::from(source);
for delimiter in strip {
reduced = strip_delimiter(graph, &reduced, delimiter)?;
}
split_per_code_point(graph, &reduced)
}
SplitMode::Delimiters(delimiters) => {
let mut parts = Vec::new();
let mut offset = 0;
while let Some((index, delimiter)) =
earliest_delimiter(graph, source, offset, &delimiters)?
{
parts.push(Value::String(source[offset..index].into()));
offset = index + delimiter.len();
}
parts.push(Value::String(source[offset..].into()));
Ok(parts)
}
}
}
pub(super) fn bi_split(graph: &ExecGraph<'_>, _n: &str, vals: Vec<Value>) -> Result<Value> {
let source = &vals[0];
if source.is_null() {
return Ok(Value::Null);
}
let Value::String(source) = source else {
return Err(Error::invalid_argument_type("split input must be STRING"));
};
let delimiters: Vec<&str> = match &vals[1] {
Value::Null => return Ok(Value::Null),
Value::String(delimiter) => vec![&**delimiter],
Value::List(delimiters) => {
if delimiters.iter().any(Value::is_null) {
return Ok(Value::Null);
}
let mut decoded: Vec<&str> = Vec::with_capacity(delimiters.len());
for delimiter in delimiters.iter() {
let Value::String(delimiter) = delimiter else {
return Err(Error::invalid_argument_type(
"split delimiters must be STRING",
));
};
decoded.push(&**delimiter);
}
decoded
}
_ => return Err(Error::invalid_argument_type("split delimiter")),
};
let delimiter_bytes = delimiters.iter().fold(0usize, |total, delimiter| {
total.saturating_add(delimiter.len())
});
let mode = split_mode(source, delimiters);
charge_split_bound(graph, source, delimiter_bytes)?;
Ok(Value::List(
split_on_delimiters(graph, source, mode)?.into(),
))
}
pub(super) fn bi_string_indexof(
_graph: &ExecGraph<'_>,
_n: &str,
vals: Vec<Value>,
) -> Result<Value> {
Ok(match (vals.first(), vals.get(1)) {
(Some(Value::Null), _) | (_, Some(Value::Null)) => Value::Null,
(Some(Value::String(input)), Some(Value::String(needle))) => {
Value::Int(
input
.find(&**needle)
.map_or(-1, |index| input[..index].chars().count() as i64),
)
}
_ => return Err(Error::invalid_argument_type("string.indexOf")),
})
}
pub(super) fn bi_string_join(graph: &ExecGraph<'_>, _n: &str, vals: Vec<Value>) -> Result<Value> {
Ok(match (vals.first(), vals.get(1)) {
(Some(Value::Null), _) | (_, Some(Value::Null)) => Value::Null,
(Some(Value::List(items)), Some(Value::String(delimiter))) => {
let strings = items
.iter()
.filter(|item| !item.is_null())
.map(|item| match item {
Value::String(value) => Ok(&**value),
_ => Err(Error::invalid_argument_type("string.join list item")),
})
.collect::<Result<Vec<_>>>()?;
let parts_bytes: usize = strings.iter().map(|part| part.len()).sum();
let delimiters_bytes = delimiter
.len()
.saturating_mul(strings.len().saturating_sub(1));
graph.charge_expression(
relate_core::str_logical_bytes("") + parts_bytes as u64 + delimiters_bytes as u64,
)?;
Value::String(strings.join(&**delimiter).into())
}
_ => return Err(Error::invalid_argument_type("string.join")),
})
}
pub(super) fn bi_string_regexreplace(
graph: &ExecGraph<'_>,
_n: &str,
vals: Vec<Value>,
) -> Result<Value> {
Ok(match (vals.first(), vals.get(1), vals.get(2)) {
(Some(Value::Null), _, _) | (_, Some(Value::Null), _) | (_, _, Some(Value::Null)) => {
Value::Null
}
(
Some(Value::String(input)),
Some(Value::String(pattern)),
Some(Value::String(replacement)),
) => {
graph.charge_expression(
(input.len() as u64)
.saturating_add(1)
.saturating_mul((replacement.len() as u64).saturating_add(1)),
)?;
let pattern = regex::Regex::new(pattern)
.map_err(|error| Error::execution(format!("InvalidRegex: {error}")))?;
Value::String(replace_all_java(&pattern, input, replacement)?.into())
}
_ => return Err(Error::invalid_argument_type("string.regexReplace")),
})
}
fn replace_all_java(pattern: ®ex::Regex, input: &str, replacement: &str) -> Result<String> {
let mut out = String::with_capacity(input.len());
let mut last = 0;
for captures in pattern.captures_iter(input) {
let whole = captures.get(0).expect("a match always has capture group 0");
out.push_str(&input[last..whole.start()]);
expand_java_replacement(replacement, &captures, &mut out)?;
last = whole.end();
}
out.push_str(&input[last..]);
Ok(out)
}
fn expand_java_replacement(
replacement: &str,
captures: ®ex::Captures<'_>,
out: &mut String,
) -> Result<()> {
let invalid = |reason: String| Error::execution(format!("InvalidArgumentValue: {reason}"));
let mut chars = replacement.chars().peekable();
while let Some(ch) = chars.next() {
match ch {
'\\' => match chars.next() {
Some(escaped) => out.push(escaped),
None => return Err(invalid("character to be escaped is missing".into())),
},
'$' => {
let group = match chars.peek().copied() {
Some('{') => {
chars.next();
let mut name = String::new();
let mut closed = false;
for ch in chars.by_ref() {
if ch == '}' {
closed = true;
break;
}
name.push(ch);
}
if !closed {
return Err(invalid(
"named capturing group is missing trailing '}'".into(),
));
}
captures
.name(&name)
.map(|matched| matched.as_str())
.ok_or_else(|| invalid(format!("no group with name {name}")))?
}
Some(next) if next.is_ascii_digit() => {
let mut digits = String::new();
while let Some(next) = chars.peek() {
if !next.is_ascii_digit() {
break;
}
digits.push(*next);
chars.next();
}
let index: usize = digits
.parse()
.map_err(|_| invalid(format!("capturing group too large: {digits}")))?;
if index >= captures.len() {
return Err(invalid(format!("no group {index}")));
}
captures
.get(index)
.map_or("null", |matched| matched.as_str())
}
_ => return Err(invalid("illegal group reference".into())),
};
out.push_str(group);
}
literal => out.push(literal),
}
}
Ok(())
}
fn string_index_arg(v: Option<&Value>, site: &IntegerArgSite) -> Result<Option<usize>> {
let Some(present) = v else {
return Ok(None);
};
let Some(n) = super::super::numeric::int_arg(present) else {
return Err(Error::invalid_argument_type(site.type_error));
};
if !(0..=i64::from(i32::MAX)).contains(&n) {
return Err(Error::argument_value_kind(
ErrorKind::NumberOutOfRange,
site.range
.expect("a string-index site states its out-of-range label"),
));
}
Ok(Some(n as usize))
}
fn null_index_arg(vals: &[Value]) -> bool {
vals.iter().skip(1).any(Value::is_null)
}
fn string_call_arg<'a>(vals: &'a [Value], what: &str) -> Result<Option<&'a str>> {
let s = match vals.first() {
None | Some(Value::Null) => return Ok(None),
Some(Value::String(s)) => s,
_ => return Err(Error::ty(what)),
};
if null_index_arg(vals) {
return Ok(None);
}
Ok(Some(s))
}
fn string_and_length<'a>(
vals: &'a [Value],
site: &IntegerArgSite,
) -> Result<Option<(&'a str, usize)>> {
let Some(s) = string_call_arg(vals, "expected string argument")? else {
return Ok(None);
};
let n = string_index_arg(vals.get(1), site)?.unwrap_or(0);
Ok(Some((s, n)))
}
pub(super) fn bi_substring(_graph: &ExecGraph<'_>, _n: &str, vals: Vec<Value>) -> Result<Value> {
let Some(s) = string_call_arg(&vals, "substring() needs a string")? else {
return Ok(Value::Null);
};
let start = string_index_arg(vals.get(1), &integer_args::SUBSTRING_START)?.unwrap_or(0);
let len = string_index_arg(vals.get(2), &integer_args::SUBSTRING_LENGTH)?.unwrap_or(usize::MAX);
Ok(Value::String(
char_range(s, start..start.saturating_add(len)).into(),
))
}
pub(super) fn bi_left(_graph: &ExecGraph<'_>, _n: &str, vals: Vec<Value>) -> Result<Value> {
let Some((s, n)) = string_and_length(&vals, &integer_args::LEFT_LENGTH)? else {
return Ok(Value::Null);
};
Ok(Value::String(char_range(s, 0..n).into()))
}
pub(super) fn bi_right(_graph: &ExecGraph<'_>, _n: &str, vals: Vec<Value>) -> Result<Value> {
let Some((s, n)) = string_and_length(&vals, &integer_args::RIGHT_LENGTH)? else {
return Ok(Value::Null);
};
Ok(Value::String(
char_range(s, s.chars().count().saturating_sub(n)..usize::MAX).into(),
))
}
#[cfg(test)]
mod tests;