#![allow(clippy::missing_docs_in_private_items)]
use std::collections::HashMap;
use crate::types::Value as TypeValue;
use super::catalog::{BUILTIN_FUNCTIONS, RESERVED_WORDS};
use super::types::ExtensionFunc;
pub trait ExtensionFunctions {
fn arity(&self, name: &str) -> Option<(usize, Option<usize>)>;
fn invoke(&self, name: &str, args: &[TypeValue]) -> Result<TypeValue, String>;
}
pub fn check_extension_name(name: &str) -> Result<(), ExtensionError> {
if RESERVED_WORDS.contains(&name) || BUILTIN_FUNCTIONS.iter().any(|entry| entry.name == name) {
return Err(ExtensionError::NameConflict(name.to_string()));
}
Ok(())
}
pub fn call_extension(
functions: &dyn ExtensionFunctions,
name: &str,
args: &[TypeValue],
) -> ExtensionCallOutcome {
let Some((min_args, max_args)) = functions.arity(name) else {
return ExtensionCallOutcome::NotFound;
};
let got = args.len();
if got < min_args || max_args.is_some_and(|max| got > max) {
return ExtensionCallOutcome::ArityMismatch {
name: name.to_string(),
min_args,
max_args,
got,
};
}
if args.iter().any(TypeValue::is_null) {
return ExtensionCallOutcome::Ok(TypeValue::Null);
}
match functions.invoke(name, args) {
Ok(value) => ExtensionCallOutcome::Ok(value),
Err(message) => ExtensionCallOutcome::Failed {
name: name.to_string(),
message,
},
}
}
pub struct ExtensionRegistry {
extensions: HashMap<String, ExtensionFunc>,
}
#[derive(Debug, Clone)]
pub enum ExtensionError {
NameConflict(String),
}
#[derive(Debug, Clone, PartialEq)]
pub enum ExtensionCallOutcome {
NotFound,
Ok(TypeValue),
ArityMismatch {
name: String,
min_args: usize,
max_args: Option<usize>,
got: usize,
},
Failed {
name: String,
message: String,
},
}
impl std::fmt::Display for ExtensionError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ExtensionError::NameConflict(name) => {
write!(
f,
"cannot register extension '{name}': conflicts with reserved word or built-in function"
)
}
}
}
}
impl std::error::Error for ExtensionError {}
impl ExtensionRegistry {
pub fn new() -> Self {
Self {
extensions: HashMap::new(),
}
}
pub fn register(
&mut self,
name: impl Into<String>,
min_args: usize,
max_args: Option<usize>,
func: impl Fn(&[TypeValue]) -> TypeValue + Send + Sync + 'static,
) -> Result<(), ExtensionError> {
let name = name.into();
check_extension_name(&name)?;
self.extensions.insert(
name.clone(),
ExtensionFunc {
name: name.clone(),
min_args,
max_args,
func: Box::new(func),
},
);
Ok(())
}
pub fn get(&self, name: &str) -> Option<&ExtensionFunc> {
self.extensions.get(name)
}
pub fn contains(&self, name: &str) -> bool {
self.extensions.contains_key(name)
}
pub fn call(&self, name: &str, args: &[TypeValue]) -> ExtensionCallOutcome {
call_extension(self, name, args)
}
}
impl ExtensionFunctions for ExtensionRegistry {
fn arity(&self, name: &str) -> Option<(usize, Option<usize>)> {
self.extensions
.get(name)
.map(|ext| (ext.min_args, ext.max_args))
}
fn invoke(&self, name: &str, args: &[TypeValue]) -> Result<TypeValue, String> {
self.extensions
.get(name)
.map(|ext| (ext.func)(args))
.ok_or_else(|| format!("extension '{name}' is not registered"))
}
}
impl Default for ExtensionRegistry {
fn default() -> Self {
Self::new()
}
}