Skip to main content

uqa_sql/semantics/functions/
production.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Normalized function identities borrow their source; case folding owns one admitted buffer.
8
9use uqa_core::{
10    memory::{Produced, ProductionControl},
11    ValueRetentionError,
12};
13
14pub enum FunctionName<'a> {
15    Borrowed(&'a str),
16    Owned(Produced<String>),
17}
18
19#[cfg(test)]
20mod tests;
21
22impl FunctionName<'_> {
23    pub fn as_str(&self) -> &str {
24        match self {
25            Self::Borrowed(name) => name,
26            Self::Owned(name) => name,
27        }
28    }
29    pub fn reserved_bytes(&self) -> usize {
30        match self {
31            Self::Borrowed(_) => 0,
32            Self::Owned(name) => name.reserved_bytes(),
33        }
34    }
35}
36
37impl std::ops::Deref for FunctionName<'_> {
38    type Target = str;
39    fn deref(&self) -> &str {
40        self.as_str()
41    }
42}
43
44pub fn lowercase_function_name_with_control<'a>(
45    name: &'a str,
46    control: &ProductionControl<'_>,
47) -> Result<FunctionName<'a>, ValueRetentionError> {
48    control.check()?;
49    if !name.bytes().any(|byte| byte.is_ascii_uppercase()) {
50        return Ok(FunctionName::Borrowed(name));
51    }
52    let (mut name, memory) = control.copy_text(name)?.into_parts();
53    name.make_ascii_lowercase();
54    Ok(FunctionName::Owned(control.finish(name, memory)?))
55}
56
57pub fn builtin_function_dispatch_name_with_control<'a>(
58    name: &'a str,
59    control: &ProductionControl<'_>,
60) -> Result<FunctionName<'a>, ValueRetentionError> {
61    let lower = lowercase_function_name_with_control(name, control)?;
62    // The shared selector only borrows when the input has already been folded.
63    let selected_length = match super::builtin_function_dispatch_name(&lower) {
64        std::borrow::Cow::Borrowed(selected) => selected.len(),
65        std::borrow::Cow::Owned(_) => unreachable!("normalized function name"),
66    };
67    let offset = lower.len() - selected_length;
68    match lower {
69        FunctionName::Borrowed(name) => Ok(FunctionName::Borrowed(&name[offset..])),
70        FunctionName::Owned(name) => {
71            let (mut name, memory) = name.into_parts();
72            name.drain(..offset);
73            Ok(FunctionName::Owned(control.finish(name, memory)?))
74        }
75    }
76}