Skip to main content

relate_executor/
function_registry.rs

1//! Canonical built-in function registry: the one table of the functions
2//! `SHOW FUNCTIONS` describes and the typed deprecation lookup the query
3//! notifications read (ADR-0363 decision 5).
4//!
5//! Mirrors [`crate::procedure_registry`]: the table and its typed lookups
6//! live here, while `show_catalog` only renders the rows. A catalog entry is
7//! deprecated exactly when its `deprecated_by` option is `Some` (01N01), and
8//! it is aggregate exactly when its own category is `Aggregating`, so there
9//! is no second flag to keep aligned either way.
10//!
11//! Every advertised function owns at least one row here — there is no
12//! placeholder entry — so a `SHOW FUNCTIONS` row always renders a real
13//! description, its registry category and a CIP-113 signature over typed
14//! parameters (ADR-0497 §8). The inventory is split by family into sibling
15//! modules so no one file carries the whole table; [`FUNCTION_META_TABLES`]
16//! is the one place that knows the parts.
17
18use crate::catalog_meta::{DeprecatedBy, ProcArgMeta};
19
20mod aggregate;
21mod graph;
22mod list;
23mod numeric;
24mod predicate;
25mod scalar;
26mod spatial;
27mod string;
28mod temporal;
29mod trig;
30mod vector;
31
32/// The registry's classification vocabulary (CIP-84): the corpus catalogue's
33/// closed fifteen-name category set, compiler-checked instead of a string
34/// literal. `as_str()` is the cell the catalogue renders.
35#[derive(Clone, Copy, Debug, PartialEq, Eq)]
36pub(crate) enum FunctionCategory {
37    Aggregating,
38    Database,
39    Graph,
40    List,
41    Logarithmic,
42    Numeric,
43    Path,
44    Predicate,
45    Scalar,
46    Spatial,
47    String,
48    Temporal,
49    Trigonometric,
50    Uuid,
51    Vector,
52}
53
54impl FunctionCategory {
55    /// The category cell `SHOW FUNCTIONS` renders (the corpus spelling).
56    pub(crate) const fn as_str(self) -> &'static str {
57        match self {
58            FunctionCategory::Aggregating => "Aggregating",
59            FunctionCategory::Database => "Database",
60            FunctionCategory::Graph => "Graph",
61            FunctionCategory::List => "List",
62            FunctionCategory::Logarithmic => "Logarithmic",
63            FunctionCategory::Numeric => "Numeric",
64            FunctionCategory::Path => "Path",
65            FunctionCategory::Predicate => "Predicate",
66            FunctionCategory::Scalar => "Scalar",
67            FunctionCategory::Spatial => "Spatial",
68            FunctionCategory::String => "String",
69            FunctionCategory::Temporal => "Temporal",
70            FunctionCategory::Trigonometric => "Trigonometric",
71            FunctionCategory::Uuid => "UUID",
72            FunctionCategory::Vector => "Vector",
73        }
74    }
75}
76
77/// One catalog row's metadata for a built-in function: its display-spelling
78/// name, the category CIP-84 classifies it under, its description and its
79/// typed parameters (the signature is derived from `args`/`return_type` by
80/// [`render_function_signature`](crate::show_catalog), except for
81/// `special_signature`).
82///
83/// The row is deprecated exactly when `deprecated_by` is `Some` (CIP-157), so
84/// the flag and its replacement cannot disagree.
85#[derive(Clone, Copy)]
86pub(crate) struct FunctionMeta {
87    /// The row's **display spelling** as the reference catalogue (Neo4j
88    /// 2026.10.1) prints it (ADR-0497 §11): the one name a row owns — the
89    /// renderer reads it for the catalogue's `name` cell and the signature —
90    /// matched case-insensitively by [`function_metas`].
91    pub(crate) name: &'static str,
92    /// The registry's classification (CIP-84).
93    pub(crate) category: FunctionCategory,
94    pub(crate) description: &'static str,
95    /// The signature **tail** for a row whose parameters are not an ordinary
96    /// parameter list — the text after the name, starting at `(` — for the
97    /// list-comprehension-styled quantifiers (`all`/`any`/`none`/`single`),
98    /// `reduce` and `allReduce`, whose grammar CIP-113 keeps as a special
99    /// case. The renderer prefixes the row's own [`name`](Self::name), so a
100    /// tail can never spell a second name.
101    pub(crate) special_signature: Option<&'static str>,
102    /// The formal parameters, in signature order. Entries carrying a
103    /// `default` keep the explicit struct literal so the default stays
104    /// visible at its entry.
105    pub(crate) args: &'static [ProcArgMeta],
106    pub(crate) return_type: &'static str,
107    /// The replacement when the function is deprecated (CIP-157's
108    /// `deprecatedBy`); `None` means not deprecated.
109    pub(crate) deprecated_by: Option<DeprecatedBy>,
110}
111
112impl FunctionMeta {
113    /// Compact entry for the common case: an ordinary parameter list, no
114    /// deprecation.
115    pub(crate) const fn described(
116        name: &'static str,
117        category: FunctionCategory,
118        description: &'static str,
119        args: &'static [ProcArgMeta],
120        return_type: &'static str,
121    ) -> Self {
122        Self {
123            name,
124            category,
125            description,
126            special_signature: None,
127            args,
128            return_type,
129            deprecated_by: None,
130        }
131    }
132
133    /// Whether the row is an aggregate: its own CIP-84 category *is* the
134    /// `aggregating` catalog column, so a row cannot report one without the
135    /// other.
136    pub(crate) fn is_aggregating(&self) -> bool {
137        matches!(self.category, FunctionCategory::Aggregating)
138    }
139}
140
141/// Every family's table, in scan order. [`function_metas`] reads this one
142/// list, so adding a module means adding its `ENTRIES` here — nothing else
143/// names the inventory.
144///
145/// Each row owns its **display spelling** as its `name` field, spelled as the
146/// reference catalogue (Neo4j 2026.10.1) prints it (ADR-0497 §11): the 42
147/// default mixed-case names (`allReduce`, `toBooleanList`,
148/// `point.withinBBox`, …) plus the three gated `coll.has*` rows carry their
149/// reference casing, every other name is the lowercase spelling. The name is
150/// the one name a row owns — the renderer reads it for the catalogue's `name`
151/// cell and the signature — and matching is case-insensitive, so the casing
152/// is a rendering fact, never an admission rule. The set of mixed-case names
153/// is pinned by
154/// `show_catalog::the_catalog_renders_the_reference_display_spellings`.
155const FUNCTION_META_TABLES: &[&[FunctionMeta]] = &[
156    scalar::ENTRIES,
157    list::ENTRIES,
158    numeric::ENTRIES,
159    trig::ENTRIES,
160    string::ENTRIES,
161    temporal::instant::ENTRIES,
162    temporal::truncate::ENTRIES,
163    temporal::gql::ENTRIES,
164    temporal::duration::ENTRIES,
165    temporal::epoch::ENTRIES,
166    temporal::format::ENTRIES,
167    aggregate::ENTRIES,
168    predicate::ENTRIES,
169    vector::ENTRIES,
170    spatial::ENTRIES,
171    graph::ENTRIES,
172];
173
174/// Every registry row, in table order: the one iteration of the inventory,
175/// shared by [`function_metas`] and the tests that walk the whole table.
176fn all_function_metas() -> impl Iterator<Item = &'static FunctionMeta> {
177    FUNCTION_META_TABLES.iter().flat_map(|table| table.iter())
178}
179
180/// The registry rows a function name produces: exactly one for every name, or
181/// several when the name has arity overloads, which CIP-113 keeps as separate
182/// signature rows (`range`, `normalize`, `round`, `btrim`, `format`,
183/// `coll.flatten`). Function calls match case-insensitively (CIP-230), so the
184/// lookup compares the call name against each row's display spelling
185/// case-insensitively, like the validator does.
186pub(crate) fn function_metas(name: &str) -> impl Iterator<Item = &'static FunctionMeta> + use<'_> {
187    all_function_metas().filter(move |meta| meta.name.eq_ignore_ascii_case(name))
188}
189
190/// CIP-230 reserved-namespace `graph.*` functions (`graph.names`,
191/// `graph.byName`, `graph.byElementId`, `graph.propertiesByName`): real
192/// Neo4j built-ins that enumerate/target constituent graphs of a *composite*
193/// (Fabric) database. A single-graph embedded engine has no composite
194/// database concept to execute these against (see MANIFEST.md CIP-61/107/
195/// 147/193/212), so they're not in `validate::KNOWN_FUNCTIONS` and can't be
196/// called -- but CIP-230's reserved-namespace list still expects them to be
197/// *discoverable* via `SHOW FUNCTIONS` (01:[1]), so they get catalog-only
198/// entries here, the same "listed but not executable" treatment the
199/// `procedure_registry` table gives several procedures.
200///
201/// Derived from the core selector table ([`relate_core::GRAPH_SELECTOR_FUNCTION_NAMES`]):
202/// the catalog-only list is exactly the selector names, in the table's
203/// order, so a selector added (or removed) there reaches `SHOW FUNCTIONS`
204/// with no second list to update. The arity lockstep test below pins each
205/// name's catalog entry to the same table.
206pub(crate) const CATALOG_ONLY_FUNCTIONS: &[&str] = &relate_core::GRAPH_SELECTOR_FUNCTION_NAMES;
207
208/// The replacement when `name` resolves to a deprecated built-in function,
209/// `None` otherwise. One typed lookup over the same table `SHOW FUNCTIONS`
210/// renders, so no caller keeps a second list of deprecated names. A name's
211/// arity rows share one `deprecated_by` (the lockstep test below), so the
212/// first row that carries a replacement speaks for every sibling.
213pub fn builtin_function_deprecation(name: &str) -> Option<DeprecatedBy> {
214    function_metas(name).find_map(|meta| meta.deprecated_by)
215}
216
217#[cfg(test)]
218mod tests {
219    use crate::catalog_meta::DeprecationForm;
220
221    use super::*;
222
223    /// The `graph.*` selector arity table in `relate-core` and the
224    /// catalog's own argument lists are one fact: a fifth selector added to
225    /// either without the other fails here.
226    #[test]
227    fn graph_selector_arities_match_the_catalog() {
228        for (name, arity) in relate_core::GRAPH_SELECTOR_FUNCTIONS {
229            let metas: Vec<&FunctionMeta> = function_metas(name).collect();
230            assert_eq!(metas.len(), 1, "{name} has no catalog entry");
231            assert_eq!(metas[0].args.len(), arity, "{name}");
232            assert!(CATALOG_ONLY_FUNCTIONS.contains(&name), "{name}");
233        }
234    }
235
236    /// The lookup reads the one function catalog: `id` is deprecated with
237    /// its `elementId` replacement (while its catalog display keeps the
238    /// CIP-157 prose sentence), `elementId` itself is not, and an unknown
239    /// name is not.
240    #[test]
241    fn function_deprecation_lookup_reads_the_function_catalog() {
242        let replacement = builtin_function_deprecation("ID").expect("id is deprecated");
243        assert_eq!(
244            replacement.display(),
245            "elementId or consider using an application-generated id"
246        );
247        assert_eq!(replacement.form(), DeprecationForm::Identifier("elementId"));
248        assert!(builtin_function_deprecation("elementId").is_none());
249        assert!(builtin_function_deprecation("no.such.function").is_none());
250    }
251
252    /// The table covers exactly the functions that can ever be listed — every
253    /// name `SHOW FUNCTIONS` can iterate (with every preview gate enabled) has
254    /// metadata, and the table invents no name the registry does not admit —
255    /// so a catalogue row can never fall back to a placeholder. Rows are
256    /// named by their display spellings (ADR-0497 §11), so each lowercases
257    /// into the advertised set: a name that names another function — or a
258    /// typo'd one — fails here.
259    #[test]
260    fn the_metadata_tables_cover_exactly_the_advertised_registry() {
261        let every_gate = relate_front::validate::every_name_gate();
262        let mut advertised: Vec<String> =
263            crate::show_catalog::advertised_function_names(every_gate)
264                .map(str::to_string)
265                .collect();
266        advertised.sort_unstable();
267        let mut catalogued: Vec<String> = all_function_metas()
268            .map(|meta| meta.name.to_ascii_lowercase())
269            .collect();
270        catalogued.sort_unstable();
271        catalogued.dedup();
272        assert_eq!(catalogued, advertised);
273    }
274
275    /// Arity sibling rows share one deprecation: every row of a name carries
276    /// the same `deprecated_by`, so the per-name deprecation lookup
277    /// ([`builtin_function_deprecation`]) cannot silently pick one sibling's
278    /// replacement over another's.
279    #[test]
280    fn arity_sibling_rows_share_one_deprecation() {
281        let mut by_name: Vec<(String, Option<DeprecatedBy>)> = all_function_metas()
282            .map(|meta| (meta.name.to_ascii_lowercase(), meta.deprecated_by))
283            .collect();
284        by_name.sort_unstable_by(|a, b| a.0.cmp(&b.0));
285        for pair in by_name.windows(2) {
286            if pair[0].0 == pair[1].0 {
287                assert_eq!(
288                    pair[0].1, pair[1].1,
289                    "{}'s arity rows disagree on their replacement",
290                    pair[0].0
291                );
292            }
293        }
294    }
295
296    /// The four recased aggregate names and the front's alias table are one
297    /// fact in two layers (ADR-0497 §11, CIP-128): `FUNCTION_ALIASES`'s
298    /// aggregate-class display — the spelling the lowering emits into IR — must equal
299    /// the catalogue name the registry renders, or `RETURN percentile_cont(x)`
300    /// and `SHOW FUNCTIONS` would print two different spellings for one
301    /// function.
302    #[test]
303    fn aggregate_alias_display_columns_match_the_registry_keys() {
304        for a in relate_front::agg::aggregate_aliases() {
305            let (alias, canonical, display) = (a.spelling, a.canonical, a.display);
306            let metas: Vec<&FunctionMeta> = function_metas(canonical).collect();
307            assert_eq!(metas.len(), 1, "{alias} -> {canonical} has no unique row");
308            assert_eq!(
309                metas[0].name, display,
310                "{canonical}'s catalogue name disagrees with the alias table's display column"
311            );
312        }
313    }
314}