use crate::error_kinds::TckErrorClass;
use crate::Error;
macro_rules! closed_vocabulary {
($name:ident, $doc:literal, [$($variant:ident),* $(,)?]) => {
#[doc = $doc]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum $name {
$($variant,)*
}
impl $name {
pub const ALL: &'static [$name] = &[$($name::$variant),*];
}
};
}
closed_vocabulary!(
ParseOption,
"The `ParseOptions` field a parse-site feature switches on, one \
variant per option. The front applies each through one total `match`.",
[
ObfuscatedLiterals,
MixedLabelSyntax,
CypherAnnotations,
PathConstruction
]
);
closed_vocabulary!(
DetectorKind,
"The front's AST detector a detected feature is checked by, one \
variant per distinct detector. The front dispatches through one \
total `match`.",
[
HybridSearch,
LocalCallables,
Float16,
PathConstruction,
Chronological,
]
);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum GateSite {
ParseOption(ParseOption),
AstDetector(DetectorKind),
GraphTypeMembership,
NameAdmission,
ProcedureDispatch,
Namespace,
CapabilityListing,
GatedElsewhere,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum GateOwner {
Parse(ParseOption),
Detect(DetectorKind),
GraphTypeWalk,
External,
}
impl GateSite {
pub fn owner(self) -> GateOwner {
match self {
GateSite::ParseOption(option) => GateOwner::Parse(option),
GateSite::AstDetector(kind) => GateOwner::Detect(kind),
GateSite::GraphTypeMembership => GateOwner::GraphTypeWalk,
GateSite::NameAdmission
| GateSite::ProcedureDispatch
| GateSite::Namespace
| GateSite::CapabilityListing
| GateSite::GatedElsewhere => GateOwner::External,
}
}
pub const ALL: &'static [GateSite] = &[
GateSite::GraphTypeMembership,
GateSite::NameAdmission,
GateSite::ProcedureDispatch,
GateSite::Namespace,
GateSite::CapabilityListing,
GateSite::GatedElsewhere,
];
}
macro_rules! preview_feature_registry {
($(($variant:ident, $doc:literal, $name:literal, [$($site:expr),* $(,)?])),* $(,)?) => {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum PreviewFeature {
$(
#[doc = $doc]
$variant,
)*
}
pub const PREVIEW_FEATURE_TABLE: &[(PreviewFeature, &str)] =
&[$((PreviewFeature::$variant, $name)),*];
pub const PREVIEW_FEATURES: &[PreviewFeature] = &[$(PreviewFeature::$variant),*];
const _: () = assert!([$(stringify!($variant)),*].len() <= 32);
$(
const _: () = assert!(
![$(stringify!($site)),*].is_empty(),
concat!(stringify!($variant), " declares no gate site")
);
)*
impl PreviewFeature {
pub fn kebab_name(self) -> &'static str {
match self {
$(PreviewFeature::$variant => $name,)*
}
}
pub fn gate_sites(self) -> &'static [GateSite] {
match self {
$(PreviewFeature::$variant => &[$($site),*],)*
}
}
pub fn from_kebab_name(name: &str) -> Option<Self> {
match name {
$($name => Some(PreviewFeature::$variant),)*
_ => None,
}
}
}
};
}
preview_feature_registry! {
(HybridSearch, "CIP-278 hybrid search `COMBINE` (reserved; lands later).", "hybrid-search", [GateSite::AstDetector(DetectorKind::HybridSearch)]),
(LocalCallables, "CIP-231 local callables: DEFINE PROCEDURE/FUNCTION, ADR-0382.", "local-callables", [GateSite::AstDetector(DetectorKind::LocalCallables)]),
(GraphTypeOptProps, "CIP-283 graph-type optional properties (`prop :: ANY` in element types).", "graph-type-opt-props", [GateSite::GraphTypeMembership]),
(GraphTypeDefaultValues, "CIP-262 graph-type property default values (`DEFAULT ON COMMIT <value expression>`).", "graph-type-default-values", [GateSite::GraphTypeMembership]),
(GraphTypeImpliedLabels, "CIP-266 graph-type implied labels that identify node element types (inheritance).", "graph-type-implied-labels", [GateSite::GraphTypeMembership]),
(
Ontology,
"The ontology feature's whole dialect surface: the `db.ontology.*` procedures \
(ADR-0378: the first non-syntax extension of ADR-0371's scope policy — the \
family's contract tracks the non-final Ontology Graph Spec and CIP-287), the \
`system_ontologies` namespace's visibility through the namespace registry's \
mapping (ADR-0593 — the namespace exists to host this feature's stored \
document, so its listing advertises the same non-final surface the procedures \
do), and the `dbms.listCapabilities` row `ontology.supported.version` \
(ADR-0741 — the supported-spec-version fact ontology tooling reads, absent \
while the opt-in is off like every other surface of the feature). Row, \
mapping and gates are removed once the spec and CIP-287 are final.",
"ontology",
[GateSite::ProcedureDispatch, GateSite::Namespace, GateSite::CapabilityListing]
),
(
ObfuscatedLiterals,
"The Neo4j obfuscated literal `******`: parsed to a dummy `false` \
for semantic analysis, never executed. Gates at the lexer, the one point the two \
behaviors differ: enabled it lexes as a literal, disabled the stream is the ordinary \
`*` tokens and the parser's own syntax error -- Neo4j's disabled form is a syntax \
error, not ADR-0371's authored preview error, so the gate never reaches the front \
detector loop (the registry names no detector site for it).",
"obfuscated-literals",
[GateSite::ParseOption(ParseOption::ObfuscatedLiterals)]
),
(
MixedLabelSyntax,
"Neo4j's mixed-label-syntax extra semantic feature: legacy \
colon-conjunction, GQL label-expression symbols and the `IS` introducer may mix \
across the label expressions of one clause (gates at parse, threaded to the parser \
as `ParseOptions`; mixing inside ONE label expression stays rejected).",
"mixed-label-syntax",
[GateSite::ParseOption(ParseOption::MixedLabelSyntax)]
),
(
Float16CoordinateTypes,
"The FLOAT16/BFLOAT16 vector coordinate types (CIP-280, ADR-0464), mirroring \
Neo4j's own configuration toggle: the types in a \
`VECTOR<…>` type expression and the `vector(<list>, <dim>, <type>)` constructor. \
Detected on the parsed AST; the disabled form is ADR-0371's authored error.",
"float16-coordinate-types",
[GateSite::AstDetector(DetectorKind::Float16)]
),
(
ChronologicalComparisons,
"Cypher 25's four chronological comparison operators \
(`a IS [NOT] BEFORE | AFTER | SAME INSTANT | SAME REPRESENTATION b`), mirroring \
Neo4j's own toggle. Detected on the \
parsed AST; the disabled form is ADR-0371's authored error.",
"chronological-comparisons",
[GateSite::AstDetector(DetectorKind::Chronological)]
),
(
CollectionZip,
"CIP-274: the `coll.zip` collection function, callable and \
`SHOW`-listed only under this opt-in (ADR-0497). A live Neo4j probe \
records the name as front-end registered but unreachable \
-- no `SHOW FUNCTIONS` row, 42N48 under CYPHER 5 and 25 -- so the default dialect must \
not advertise it. Row and gate are deleted when a Neo4j release ships the function.",
"coll-zip",
[GateSite::NameAdmission]
),
(
CollectionHas,
"CIP-286: the `coll.hasAnyOf`/`coll.hasAllOf`/\
`coll.hasNoneOf` collection functions, callable and `SHOW`-listed only under this \
opt-in (ADR-0497). One row for the three-name family; deleted when CIP-286 ships.",
"coll-has",
[GateSite::NameAdmission]
),
(
CypherAnnotations,
"CIP-281 Cypher annotations: clause-level `@name(params)` markers before a \
clause, parsed and semantically checked, then discarded (no runtime effect). \
Gates at the lexer, the one point the two behaviors differ: enabled, `@` lexes \
as the annotation introducer; disabled, it is the ordinary `unexpected \
character: @` syntax error. Row and gate are deleted when the CIP ships in a \
release.",
"cypher-annotations",
[GateSite::ParseOption(ParseOption::CypherAnnotations)]
),
(
GqlStddevAliases,
"CIP-245's `stddev_samp`/`stddev_pop` spellings (ADR-0497): the corpus catalogue lists \
only the canonical `stdev_samp`/`stdev_pop`, and Neo4j 2026.05 answers 42N48 for the \
GQL spellings, so the default dialect advertises and dispatches only the `stdev_*` \
rows. The gate keeps the `@doc`-derived 78/78 reachable. Deleted when a release \
registers the spellings (or the scenarios are re-pinned).",
"gql-stddev-aliases",
[GateSite::NameAdmission]
),
(
GraphTypeShowVariants,
"CIP-275 graph-type display variants of SHOW CURRENT GRAPH TYPE: consolidated and flattened.",
"graph-type-show-variants",
[GateSite::GraphTypeMembership]
),
(
PathConstruction,
"The `PATH [n1, r1, n2, ...]` path constructor: builds a path value from an \
alternating node, relationship, ... list. Detected at the parse point (the \
`PATH` word before `[`); the disabled form is ADR-0371's authored error.",
"path-construction",
[GateSite::ParseOption(ParseOption::PathConstruction), GateSite::AstDetector(DetectorKind::PathConstruction)]
),
(
PathConcatenation,
"The `p1 || p2` path concatenation: joins two paths that share a boundary \
node. Gates the `||` operator over path operands at evaluation; the disabled \
form is the existing `||` operand type error, not the authored error.",
"path-concatenation",
[GateSite::GatedElsewhere]
),
(
VortexStore,
"The Vortex columnar property store (ADR-0665), experimental: an \
alternative storage representation behind the executor's PropStore \
seam. The registry's first storage-representation row (ADR-0703): \
the gate is at `Database::open`, not at a parse or dispatch site — \
the row attaches the store for every open in the process (the typed \
`OpenOptions::vortex_store` field opts in one open), and a build \
without the `vortex-store` cargo feature fails the open closed \
naming the feature. While disabled nothing changes: the default \
compact records answer, and no statement can ask for the store, so \
there is no authored disabled-error.",
"vortex-store",
[GateSite::GatedElsewhere]
),
}
fn known_feature_names() -> String {
PREVIEW_FEATURE_TABLE
.iter()
.map(|(_, name)| *name)
.collect::<Vec<_>>()
.join(", ")
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PreviewFeatures(u32);
impl Default for PreviewFeatures {
fn default() -> Self {
Self::none()
}
}
impl PreviewFeatures {
pub fn none() -> Self {
Self(0)
}
pub fn parse_named(source: &str, raw: &str) -> Result<Self, Error> {
if raw.trim().is_empty() {
return Ok(Self::none());
}
Self::from_names(source, raw.split(',').map(str::trim))
}
pub fn from_names<'a>(
source: &str,
names: impl IntoIterator<Item = &'a str>,
) -> Result<Self, Error> {
names.into_iter().try_fold(Self::none(), |enabled, name| {
let feature = PreviewFeature::from_kebab_name(name).ok_or_else(|| {
Error::semantic(format!(
"{}: invalid {source} value: unknown preview feature \
'{name}' (known features: {})",
TckErrorClass::SemanticError.as_str(),
known_feature_names(),
))
})?;
Ok(enabled.with_feature(feature))
})
}
pub fn parse_optional(source: &str, raw: Option<&str>) -> Result<Self, Error> {
raw.map_or(Ok(Self::none()), |raw| Self::parse_named(source, raw))
}
pub fn parse(raw: &str) -> Result<Self, Error> {
Self::parse_named(PREVIEW_ENV_VAR, raw)
}
pub fn enabled(self, feature: PreviewFeature) -> bool {
self.0 & (1 << (feature as u32)) != 0
}
pub fn with_feature(self, feature: PreviewFeature) -> Self {
Self(self.0 | (1 << (feature as u32)))
}
pub fn union(self, other: Self) -> Self {
Self(self.0 | other.0)
}
pub fn require(self, feature: PreviewFeature) -> Result<(), Error> {
if self.enabled(feature) {
Ok(())
} else {
Err(preview_feature_disabled(feature))
}
}
}
pub const PREVIEW_ENV_VAR: &str = "RELATE_PREVIEW";
pub const STORE_CONFIG_FILE: &str = "relate.yaml";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PreviewSource {
Env,
Config,
Option,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct PreviewSources {
pub env: PreviewFeatures,
pub config: PreviewFeatures,
pub option: PreviewFeatures,
}
impl PreviewSources {
fn parts(&self) -> [(PreviewSource, PreviewFeatures); 3] {
let Self {
env,
config,
option,
} = *self;
[
(PreviewSource::Env, env),
(PreviewSource::Config, config),
(PreviewSource::Option, option),
]
}
pub fn union(&self) -> PreviewFeatures {
self.parts()
.into_iter()
.fold(PreviewFeatures::none(), |set, (_, part)| set.union(part))
}
pub fn carriers(&self, feature: PreviewFeature) -> impl Iterator<Item = PreviewSource> {
self.parts()
.into_iter()
.filter(move |(_, part)| part.enabled(feature))
.map(|(source, _)| source)
}
}
pub fn preview_feature_disabled_text(feature: PreviewFeature) -> String {
let name = feature.kebab_name();
format!(
"{}: preview feature '{name}' is not enabled: set RELATE_PREVIEW={name}",
TckErrorClass::SemanticError.as_str(),
)
}
pub(crate) fn preview_feature_disabled(feature: PreviewFeature) -> Error {
Error::semantic(preview_feature_disabled_text(feature))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn registry_names_are_unique_and_round_trip() {
let mut seen = std::collections::HashSet::new();
for (feature, name) in PREVIEW_FEATURE_TABLE {
assert_eq!(feature.kebab_name(), *name);
assert!(seen.insert(*name), "duplicate name {name}");
assert_eq!(PreviewFeature::from_kebab_name(name), Some(*feature));
}
assert_eq!(PreviewFeature::from_kebab_name("nope"), None);
}
#[test]
fn gate_sites_never_repeat_within_a_row() {
for feature in PREVIEW_FEATURES {
let mut seen = std::collections::HashSet::new();
for site in feature.gate_sites() {
assert!(
seen.insert(*site),
"{} repeats {site:?}",
feature.kebab_name()
);
}
}
}
#[test]
fn every_declared_payload_less_site_is_enumerated() {
for feature in PREVIEW_FEATURES {
for site in feature.gate_sites() {
if matches!(site.owner(), GateOwner::Parse(_) | GateOwner::Detect(_)) {
continue;
}
assert!(
GateSite::ALL.contains(site),
"{} declares {site:?}, which GateSite::ALL does not enumerate",
feature.kebab_name()
);
}
}
}
#[test]
fn parse_empty_and_unset_value_enable_nothing() {
assert_eq!(PreviewFeatures::parse("").unwrap(), PreviewFeatures::none());
assert_eq!(
PreviewFeatures::parse(" ").unwrap(),
PreviewFeatures::none()
);
for feature in PREVIEW_FEATURES {
assert!(!PreviewFeatures::none().enabled(*feature));
}
}
#[test]
fn parse_comma_lists_and_whitespace() {
let features =
PreviewFeatures::parse(" hybrid-search,graph-type-implied-labels , local-callables ")
.unwrap();
assert!(features.enabled(PreviewFeature::HybridSearch));
assert!(features.enabled(PreviewFeature::GraphTypeImpliedLabels));
assert!(features.enabled(PreviewFeature::LocalCallables));
assert!(!features.enabled(PreviewFeature::GraphTypeOptProps));
assert!(!features.enabled(PreviewFeature::GraphTypeDefaultValues));
assert_eq!(
PreviewFeatures::parse("hybrid-search, hybrid-search").unwrap(),
PreviewFeatures::parse("hybrid-search").unwrap(),
);
}
#[test]
fn parse_unknown_name_fails_closed_naming_known_names() {
let error = PreviewFeatures::parse("hybrid-search,bogus").unwrap_err();
assert!(matches!(error, Error::Semantic(_)), "{error}");
let display = error.to_string();
assert!(
display.contains("unknown preview feature 'bogus'"),
"{display}"
);
for (_, name) in PREVIEW_FEATURE_TABLE {
assert!(display.contains(name), "{display} misses {name}");
}
let error = PreviewFeatures::parse("hybrid-search,,local-callables").unwrap_err();
assert!(
error.to_string().contains("unknown preview feature ''"),
"{}",
error
);
}
#[test]
fn parse_each_registered_name_enables_exactly_that_feature() {
for feature in PREVIEW_FEATURES {
let enabled = PreviewFeatures::parse(feature.kebab_name()).unwrap();
assert!(enabled.enabled(*feature), "{}", feature.kebab_name());
for other in PREVIEW_FEATURES {
if other != feature {
assert!(
!enabled.enabled(*other),
"{} also enabled {}",
feature.kebab_name(),
other.kebab_name()
);
}
}
}
}
#[test]
fn require_gates_with_the_authored_disabled_error() {
let features = PreviewFeatures::parse("local-callables").unwrap();
assert!(features.require(PreviewFeature::LocalCallables).is_ok());
let error = features.require(PreviewFeature::HybridSearch).unwrap_err();
assert_eq!(
error.to_string(),
"semantic error: SemanticError: preview feature 'hybrid-search' is not enabled: \
set RELATE_PREVIEW=hybrid-search"
);
for (feature, name) in PREVIEW_FEATURE_TABLE {
let error = preview_feature_disabled(*feature);
assert!(
error.to_string().ends_with(&format!(
"preview feature '{name}' is not enabled: set RELATE_PREVIEW={name}"
)),
"{}",
error
);
}
}
#[test]
fn the_sources_union_derives_additively_from_its_parts() {
let sources = PreviewSources {
env: PreviewFeatures::parse("hybrid-search").unwrap(),
config: PreviewFeatures::parse("ontology").unwrap(),
option: PreviewFeatures::parse("local-callables").unwrap(),
};
let union = sources.union();
for feature in [PreviewFeature::HybridSearch, PreviewFeature::Ontology] {
assert!(union.enabled(feature), "{}", feature.kebab_name());
}
assert!(!union.enabled(PreviewFeature::Float16CoordinateTypes));
assert_eq!(PreviewSources::default().union(), PreviewFeatures::none());
assert!(sources.env.enabled(PreviewFeature::HybridSearch));
assert!(!sources.env.enabled(PreviewFeature::Ontology));
assert!(sources.config.enabled(PreviewFeature::Ontology));
}
#[test]
fn the_carriers_report_every_enabling_source_in_order() {
let stacked = PreviewSources {
env: PreviewFeatures::parse("ontology").unwrap(),
option: PreviewFeatures::parse("ontology").unwrap(),
..PreviewSources::default()
};
assert_eq!(
stacked
.carriers(PreviewFeature::Ontology)
.collect::<Vec<_>>(),
[PreviewSource::Env, PreviewSource::Option]
);
assert_eq!(stacked.carriers(PreviewFeature::HybridSearch).count(), 0);
}
#[test]
fn from_names_resolves_each_name_without_the_comma_grammar() {
let error = PreviewFeatures::from_names("src", ["ontology,coll-zip"]).unwrap_err();
assert!(
error
.to_string()
.contains("unknown preview feature 'ontology,coll-zip'"),
"{error}"
);
assert!(PreviewFeatures::from_names("src", [""]).is_err());
assert_eq!(
PreviewFeatures::from_names("src", []).unwrap(),
PreviewFeatures::none()
);
assert!(PreviewFeatures::from_names("src", ["ontology", "coll-zip"])
.unwrap()
.enabled(PreviewFeature::CollectionZip));
}
}