use crate::error::{Result, SQLError};
use std::cell::Cell;
use std::ops::Range;
use uqa_core::memory::{MemoryError, Produced, ProductionControl, ProductionString, ProductionVec};
use uqa_pg_regex::{
CompileFlags, MatchSpan, Regex, RegexCollation, RegexError, MAX_ALLOC_SIZE, REG_ESPACE,
};
mod allowance;
pub(super) use allowance::Allowance;
pub(super) struct RegexCall<'c> {
control: ProductionControl<'c>,
refusal: Cell<Option<MemoryError>>,
}
impl<'c> RegexCall<'c> {
pub(super) fn new(control: &ProductionControl<'c>) -> Self {
Self {
control: *control,
refusal: Cell::new(None),
}
}
pub(super) fn allowance(&self) -> Allowance<'_, 'c> {
Allowance::new(self)
}
pub(super) fn compile<'r>(
&self,
pattern: &str,
flags: CompileFlags,
collation: u32,
allowance: &'r mut Allowance<'_, 'c>,
) -> Result<Regex<'r>> {
self.check()?;
code_point_buffer_bytes(pattern.len())?;
let collation = RegexCollation::from_oid(collation)
.map_err(|error| self.failure(error, "invalid regular expression"))?;
Regex::compile(pattern, flags, collation, allowance)
.map_err(|error| self.failure(error, "invalid regular expression"))
}
pub(super) fn execute(
&self,
regex: &mut Regex<'_>,
input: &[u32],
start: usize,
spans: &mut [MatchSpan],
) -> Result<bool> {
regex
.exec(input, start, spans)
.map_err(|error| self.failure(error, "regular expression failed"))
}
pub(super) fn check(&self) -> Result<()> {
self.control.check()?;
crate::expr::check_statement_cancellation()?;
Ok(())
}
fn refuse(&self, error: MemoryError) {
let first = self.refusal.take().unwrap_or(error);
self.refusal.set(Some(first));
}
fn cancel_requested(&self) -> bool {
self.control.check_cancellation().is_err()
|| crate::expr::check_statement_cancellation().is_err()
}
fn failure(&self, error: RegexError, context: &str) -> SQLError {
if matches!(
error,
RegexError::Code(REG_ESPACE) | RegexError::OutOfMemory
) {
if let Some(refusal) = self.refusal.take() {
return refusal.into();
}
}
match error {
RegexError::Code(_) => engine_error(error, context),
RegexError::Cancelled => match self
.control
.check_cancellation()
.and_then(|()| crate::expr::check_statement_cancellation())
{
Err(cancelled) => cancelled.into(),
Ok(()) => SQLError::Internal(
"the regular expression engine stopped for a cancellation the statement does not report".into(),
),
},
other => diagnostic(other),
}
}
}
fn diagnostic(error: RegexError) -> SQLError {
SQLError::Diagnostic {
sqlstate: error.sqlstate().unwrap_or("XX000").into(),
message: error.message().to_string(),
detail: None,
hint: error.hint().map(Into::into),
}
}
fn code_point_buffer_bytes(length: usize) -> Result<usize> {
let slots = length.saturating_add(1);
let bytes = slots.checked_mul(size_of::<u32>()).ok_or_else(|| {
diagnostic(RegexError::InvalidAllocationProduct(
slots,
size_of::<u32>(),
))
})?;
if bytes > MAX_ALLOC_SIZE {
return Err(diagnostic(RegexError::InvalidAllocationSize(bytes)));
}
Ok(bytes)
}
fn engine_error(error: RegexError, context: &str) -> SQLError {
SQLError::Routine {
sqlstate: "2201B".into(),
message: format!("{context}: {}", error.message()),
}
}
pub(super) fn code_points(
text: &str,
control: &ProductionControl<'_>,
) -> Result<Produced<Vec<u32>>> {
code_point_buffer_bytes(text.len())?;
let mut points = ProductionVec::new(*control);
points.reserve(text.chars().count())?;
for character in text.chars() {
points.push_copy(u32::from(character))?;
}
points.finish().map_err(Into::into)
}
pub(super) fn push_text(
output: &mut ProductionString<'_>,
points: &[u32],
range: Range<usize>,
) -> Result<()> {
for &point in span_points(points, range)? {
let character = char::from_u32(point).ok_or_else(|| {
SQLError::Internal(format!(
"regular expression input held invalid code point {point}"
))
})?;
output.push(character)?;
}
Ok(())
}
pub(super) fn text(
points: &[u32],
range: Range<usize>,
control: &ProductionControl<'_>,
) -> Result<Produced<String>> {
let mut output = ProductionString::new(*control);
output.reserve(
span_points(points, range.clone())?
.iter()
.map(|point| char::from_u32(*point).map_or(0, char::len_utf8))
.sum(),
)?;
push_text(&mut output, points, range)?;
output.finish().map_err(Into::into)
}
fn span_points(points: &[u32], range: Range<usize>) -> Result<&[u32]> {
points.get(range).ok_or_else(|| {
SQLError::Internal("a regular expression span lies outside its input".into())
})
}
pub(super) fn whole_match(span: MatchSpan) -> Result<Range<usize>> {
span.range().ok_or_else(|| {
SQLError::Internal("the regular expression engine reported a match without its span".into())
})
}
#[cfg(test)]
mod tests;