Skip to main content

uqa_sql/binding/production/
names.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Lexical binding names own their admitted text and exact ordered nodes independently.
8
9use crate::SQLError;
10use std::{borrow::Borrow, cmp::Ordering, collections::BTreeMap};
11use uqa_core::memory::{BudgetedMapIter, OwnedMap, Produced, ProductionControl};
12
13pub struct BindingName(Produced<String>);
14impl Borrow<str> for BindingName {
15    fn borrow(&self) -> &str {
16        &self.0
17    }
18}
19impl PartialEq for BindingName {
20    fn eq(&self, other: &Self) -> bool {
21        self.0.eq(&other.0)
22    }
23}
24impl Eq for BindingName {}
25impl PartialOrd for BindingName {
26    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
27        Some(self.cmp(other))
28    }
29}
30impl Ord for BindingName {
31    fn cmp(&self, other: &Self) -> Ordering {
32        self.0.as_str().cmp(other.0.as_str())
33    }
34}
35
36/// Each entry releases its name and node when removed. Values retain their own immutable metadata owners.
37pub struct BindingMap<V> {
38    entries: OwnedMap<BindingName, V>,
39}
40impl<V> Default for BindingMap<V> {
41    fn default() -> Self {
42        Self {
43            entries: OwnedMap::new(),
44        }
45    }
46}
47impl<V> BindingMap<V> {
48    pub fn new() -> Self {
49        Self::default()
50    }
51    pub fn len(&self) -> usize {
52        self.entries.len()
53    }
54    pub fn is_empty(&self) -> bool {
55        self.entries.is_empty()
56    }
57    pub fn clear(&mut self) {
58        self.entries.clear();
59    }
60    pub fn get(&self, name: &str) -> Option<&V> {
61        self.entries.get(name)
62    }
63    /// Compare a borrowed decoded SQL name directly with ordered keys, including escaped quoted references.
64    pub fn get_name(&self, name: uqa_core::RelationName<'_>) -> Option<&V> {
65        self.entries
66            .get_by(|key| name.cmp(&uqa_core::RelationName::decoded(&key.0)))
67    }
68    pub fn get_mut(&mut self, name: &str) -> Option<&mut V> {
69        self.entries.get_mut(name)
70    }
71    pub fn contains_key(&self, name: &str) -> bool {
72        self.entries.contains_key(name)
73    }
74    pub fn remove(&mut self, name: &str) -> Option<V> {
75        self.entries.remove(name)
76    }
77    pub fn extract(&mut self, name: &str) -> Self {
78        Self {
79            entries: self.entries.extract(name),
80        }
81    }
82    pub fn append(&mut self, entries: Self) {
83        self.entries.append(entries.entries);
84    }
85    pub fn retain(&mut self, mut keep: impl FnMut(&String, &mut V) -> bool) {
86        self.entries.retain(|name, value| keep(&name.0, value));
87    }
88    pub fn iter(&self) -> BindingIter<'_, V> {
89        BindingIter(self.entries.iter())
90    }
91    pub fn keys(&self) -> impl ExactSizeIterator<Item = &String> {
92        self.iter().map(|(name, _)| name)
93    }
94    pub fn values(&self) -> impl ExactSizeIterator<Item = &V> {
95        self.iter().map(|(_, value)| value)
96    }
97    pub fn insert(&mut self, name: String, value: V) -> Option<V> {
98        self.entries.insert(
99            BindingName(
100                ProductionControl::uncontrolled()
101                    .finish(name, None)
102                    .expect("ordinary binding name"),
103            ),
104            value,
105        )
106    }
107    pub fn insert_with_control(
108        &mut self,
109        name: &str,
110        value: V,
111        control: &ProductionControl<'_>,
112    ) -> Result<Option<V>, SQLError> {
113        control.check()?;
114        if let Some(previous) = self.get_mut(name) {
115            return Ok(Some(std::mem::replace(previous, value)));
116        }
117        let name = BindingName(control.copy_text(name)?);
118        Ok(match control.budget() {
119            Some(budget) => self.entries.insert_budgeted(name, value, budget)?,
120            None => self.entries.insert(name, value),
121        })
122    }
123    /// The callback decides how each value shares or independently produces its own payload; this map never assumes Clone admits an allocating value.
124    pub fn copy_with_control(
125        &self,
126        control: &ProductionControl<'_>,
127        mut value: impl FnMut(&V) -> Result<V, SQLError>,
128    ) -> Result<Self, SQLError> {
129        let mut output = Self::new();
130        for (name, item) in self {
131            control.check()?;
132            output.insert_with_control(name, value(item)?, control)?;
133        }
134        Ok(output)
135    }
136}
137impl<V: Clone> Clone for BindingMap<V> {
138    fn clone(&self) -> Self {
139        self.iter()
140            .map(|(name, value)| (name.clone(), value.clone()))
141            .collect()
142    }
143}
144impl<V> FromIterator<(String, V)> for BindingMap<V> {
145    fn from_iter<I: IntoIterator<Item = (String, V)>>(entries: I) -> Self {
146        let mut output = Self::new();
147        for (name, value) in entries {
148            output.insert(name, value);
149        }
150        output
151    }
152}
153impl<V> From<BTreeMap<String, V>> for BindingMap<V> {
154    fn from(entries: BTreeMap<String, V>) -> Self {
155        entries.into_iter().collect()
156    }
157}
158impl<V> std::ops::Index<&str> for BindingMap<V> {
159    type Output = V;
160    fn index(&self, name: &str) -> &V {
161        self.get(name).expect("bound lexical name")
162    }
163}
164pub struct BindingIter<'a, V>(BudgetedMapIter<'a, BindingName, V>);
165impl<'a, V> Iterator for BindingIter<'a, V> {
166    type Item = (&'a String, &'a V);
167    fn next(&mut self) -> Option<Self::Item> {
168        self.0.next().map(|(name, value)| (&*name.0, value))
169    }
170    fn size_hint(&self) -> (usize, Option<usize>) {
171        self.0.size_hint()
172    }
173}
174impl<V> ExactSizeIterator for BindingIter<'_, V> {}
175impl<V> std::iter::FusedIterator for BindingIter<'_, V> {}
176impl<'a, V> IntoIterator for &'a BindingMap<V> {
177    type Item = (&'a String, &'a V);
178    type IntoIter = BindingIter<'a, V>;
179    fn into_iter(self) -> Self::IntoIter {
180        self.iter()
181    }
182}
183
184#[derive(Default, Clone)]
185pub struct BindingNameSet(BindingMap<()>);
186impl BindingNameSet {
187    pub fn new() -> Self {
188        Self::default()
189    }
190    pub fn contains(&self, name: &str) -> bool {
191        self.0.contains_key(name)
192    }
193    pub fn contains_name(&self, name: uqa_core::RelationName<'_>) -> bool {
194        self.0.get_name(name).is_some()
195    }
196    pub fn insert(&mut self, name: String) -> bool {
197        self.0.insert(name, ()).is_none()
198    }
199    pub fn remove(&mut self, name: &str) -> bool {
200        self.0.remove(name).is_some()
201    }
202    pub fn extract(&mut self, name: &str) -> Self {
203        Self(self.0.extract(name))
204    }
205    pub fn append(&mut self, entries: Self) {
206        self.0.append(entries.0);
207    }
208    pub fn clear(&mut self) {
209        self.0.clear();
210    }
211    pub fn is_empty(&self) -> bool {
212        self.0.is_empty()
213    }
214    pub fn iter(&self) -> impl ExactSizeIterator<Item = &String> {
215        self.0.keys()
216    }
217    pub fn insert_with_control(
218        &mut self,
219        name: &str,
220        control: &ProductionControl<'_>,
221    ) -> Result<bool, SQLError> {
222        self.0
223            .insert_with_control(name, (), control)
224            .map(|old| old.is_none())
225    }
226    pub fn copy_with_control(&self, control: &ProductionControl<'_>) -> Result<Self, SQLError> {
227        self.0.copy_with_control(control, |()| Ok(())).map(Self)
228    }
229}
230impl FromIterator<String> for BindingNameSet {
231    fn from_iter<I: IntoIterator<Item = String>>(entries: I) -> Self {
232        Self(entries.into_iter().map(|name| (name, ())).collect())
233    }
234}
235
236impl Extend<String> for BindingNameSet {
237    fn extend<I: IntoIterator<Item = String>>(&mut self, names: I) {
238        for name in names {
239            self.insert(name);
240        }
241    }
242}
243impl<'a> IntoIterator for &'a BindingNameSet {
244    type Item = &'a String;
245    type IntoIter = BindingNames<'a>;
246    fn into_iter(self) -> Self::IntoIter {
247        BindingNames(self.0.iter())
248    }
249}
250pub struct BindingNames<'a>(BindingIter<'a, ()>);
251impl<'a> Iterator for BindingNames<'a> {
252    type Item = &'a String;
253    fn next(&mut self) -> Option<Self::Item> {
254        self.0.next().map(|(name, ())| name)
255    }
256    fn size_hint(&self) -> (usize, Option<usize>) {
257        self.0.size_hint()
258    }
259}
260impl ExactSizeIterator for BindingNames<'_> {}
261impl std::iter::FusedIterator for BindingNames<'_> {}