use relate_core::integer_args::{self, range_text, IntegerArgSite};
use relate_core::{invalid_argument_text, number_out_of_range_text, Error, Result, Value};
use relate_ir::{Expr, UnaryOp};
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum LiteralKind {
Null,
Bool,
Int,
Float,
List,
Map,
Other,
}
pub(crate) fn static_arg_value(expr: &Expr) -> Option<Value> {
match expr {
Expr::Null => Some(Value::Null),
Expr::Bool(value) => Some(Value::Bool(*value)),
Expr::Int(value) => Some(Value::Int(*value)),
Expr::Float(value) => Some(Value::Float(*value)),
Expr::String(value) => Some(Value::String(value.as_str().into())),
Expr::RuntimeValue(value) => Some(value.clone()),
Expr::Parameter(name) => relate_core::auto_literal(name),
Expr::List(items) => Value::checked_list(
items
.iter()
.map(static_arg_value)
.collect::<Option<Vec<_>>>()?,
)
.ok(),
Expr::Map(pairs) => {
let map = pairs
.iter()
.map(|(key, value)| Some((key.clone(), static_arg_value(value)?)))
.collect::<Option<std::collections::BTreeMap<_, _>>>()?;
Value::checked_map(map).ok()
}
Expr::Unary {
op: UnaryOp::Plus,
expr,
} => static_arg_value(expr),
Expr::Unary {
op: UnaryOp::Minus,
expr,
} => match static_arg_value(expr)? {
Value::Int(value) => value.checked_neg().map(Value::Int),
Value::Float(value) => Some(Value::Float(-value)),
_ => None,
},
_ => None,
}
}
pub(crate) fn static_literal(expr: &Expr) -> Option<LiteralKind> {
match expr {
Expr::List(_) => Some(LiteralKind::List),
Expr::Map(_) => Some(LiteralKind::Map),
Expr::Unary {
op: UnaryOp::Minus | UnaryOp::Plus,
expr,
} => static_literal(expr),
other => static_arg_value(other).map(|value| literal_kind(&value)),
}
}
fn literal_kind(value: &Value) -> LiteralKind {
match value {
Value::Null => LiteralKind::Null,
Value::Bool(_) => LiteralKind::Bool,
Value::Int(_) => LiteralKind::Int,
Value::Float(_) => LiteralKind::Float,
Value::List(_) => LiteralKind::List,
Value::Map(_) => LiteralKind::Map,
Value::String(_)
| Value::Node(_)
| Value::Relationship(_)
| Value::Path(_)
| Value::Temporal(_)
| Value::Point(_)
| Value::Uuid(_)
| Value::Vector { .. }
| Value::Bytes(_) => LiteralKind::Other,
}
}
pub(crate) fn is_static_non_bool(expr: &Expr) -> bool {
matches!(expr, Expr::CountStar)
|| matches!(
static_literal(expr),
Some(kind) if !matches!(kind, LiteralKind::Bool | LiteralKind::Null)
)
}
fn is_float_literal(expr: &Expr) -> bool {
static_literal(expr) == Some(LiteralKind::Float)
}
pub(crate) fn float_integer_site(expr: &Expr) -> Option<&'static IntegerArgSite> {
match expr {
Expr::Subscript { index, .. } if is_float_literal(index) => Some(&integer_args::LIST_INDEX),
Expr::Slice { start, .. } if start.as_deref().is_some_and(is_float_literal) => {
Some(&integer_args::SLICE_START)
}
Expr::Slice { end, .. } if end.as_deref().is_some_and(is_float_literal) => {
Some(&integer_args::SLICE_END)
}
_ => None,
}
}
pub(crate) fn reject_float_integer_site(expr: &Expr) -> Result<()> {
match float_integer_site(expr) {
Some(site) => Err(Error::invalid_argument_type(site.type_error)),
None => Ok(()),
}
}
pub(crate) fn is_non_integer_literal(expr: &Expr) -> bool {
matches!(
static_literal(expr),
Some(kind) if !matches!(kind, LiteralKind::Int | LiteralKind::Null)
)
}
pub(crate) fn reject_non_integer_literal(expr: &Expr, detail: &str) -> Result<()> {
if is_non_integer_literal(expr) {
return Err(Error::invalid_argument_type(detail));
}
Ok(())
}
#[derive(Clone, Copy)]
pub(crate) struct ModifierGate {
accepts: &'static [LiteralKind],
min: f64,
any_minus_out_of_range: bool,
range_text: fn(&'static str) -> String,
}
impl ModifierGate {
pub(crate) const POSITIVE: Self = Self {
accepts: &[LiteralKind::Int, LiteralKind::Null],
min: 1.0,
any_minus_out_of_range: false,
range_text: |detail| invalid_argument_text(detail),
};
pub(crate) const NON_NEGATIVE: Self = Self {
accepts: &[LiteralKind::Int, LiteralKind::Float],
min: 0.0,
any_minus_out_of_range: true,
range_text: |detail| number_out_of_range_text(detail),
};
fn out_of_range(&self, expr: &Expr) -> bool {
if self.any_minus_out_of_range
&& matches!(
expr,
Expr::Unary {
op: UnaryOp::Minus,
..
}
)
{
return true;
}
let (number, kind) = match static_arg_value(expr) {
Some(Value::Int(value)) => (value as f64, LiteralKind::Int),
Some(Value::Float(value)) => (value, LiteralKind::Float),
_ => return false,
};
number < self.min && (self.accepts.contains(&kind) || number.is_sign_negative())
}
fn rejects_type(&self, expr: &Expr) -> bool {
static_literal(expr).is_some_and(|kind| !self.accepts.contains(&kind))
}
}
pub(crate) fn check_modifier_literal(
expr: &Expr,
site: &IntegerArgSite,
gate: ModifierGate,
) -> Result<()> {
if gate.out_of_range(expr) {
return Err(Error::syntax((gate.range_text)(range_text(site))));
}
if gate.rejects_type(expr) {
return Err(Error::invalid_argument_type(site.type_error).into_syntax());
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use relate_core::integer_args::{TX_BATCH_SIZE, TX_RETRY_DURATION};
fn neg(expr: Expr) -> Expr {
Expr::Unary {
op: UnaryOp::Minus,
expr: Box::new(expr),
}
}
fn rejection(result: Result<()>) -> String {
result.expect_err("the literal is rejected").to_string()
}
#[test]
fn the_positive_gate_rejects_every_non_positive_spelling_through_one_walk() {
for expr in [
Expr::Int(0),
Expr::Int(-1),
neg(Expr::Int(1)),
neg(Expr::Float(1.5)),
] {
let text = rejection(check_modifier_literal(
&expr,
&TX_BATCH_SIZE,
ModifierGate::POSITIVE,
));
assert!(
text.contains("InvalidArgument: batch size must be a positive integer"),
"{text}"
);
}
check_modifier_literal(&Expr::Int(3), &TX_BATCH_SIZE, ModifierGate::POSITIVE)
.expect("positive passes");
let text = rejection(check_modifier_literal(
&Expr::Float(1.5),
&TX_BATCH_SIZE,
ModifierGate::POSITIVE,
));
assert!(text.contains("batch size must be an integer"), "{text}");
}
#[test]
fn the_duration_gate_splits_range_from_type_in_one_match() {
for expr in [
neg(Expr::Int(0)),
neg(Expr::Int(1)),
neg(Expr::Float(0.5)),
Expr::Int(-2),
] {
let text = rejection(check_modifier_literal(
&expr,
&TX_RETRY_DURATION,
ModifierGate::NON_NEGATIVE,
));
assert!(
text.contains("NumberOutOfRange: retry duration must be non-negative"),
"{text}"
);
}
for expr in [
Expr::Null,
Expr::Bool(true),
Expr::String("x".into()),
Expr::List(vec![]),
Expr::Map(vec![]),
] {
let text = rejection(check_modifier_literal(
&expr,
&TX_RETRY_DURATION,
ModifierGate::NON_NEGATIVE,
));
assert!(text.contains("retry duration must be numeric"), "{text}");
}
for expr in [Expr::Int(0), Expr::Float(2.5)] {
check_modifier_literal(&expr, &TX_RETRY_DURATION, ModifierGate::NON_NEGATIVE)
.expect("non-negative passes");
}
}
#[test]
fn a_resolved_plan_cache_placeholder_reads_like_the_literal_it_replaced() {
use relate_core::AutoLiteralGuard;
use std::collections::BTreeMap;
let params = BTreeMap::from([
("__AUTO_0__".to_string(), Value::Int(-4)),
("__AUTO_1__".to_string(), Value::Int(7)),
]);
let _guard = AutoLiteralGuard::install(¶ms);
let placeholder = |name: &str| Expr::Parameter(name.to_string());
let text = rejection(check_modifier_literal(
&placeholder("__AUTO_0__"),
&TX_RETRY_DURATION,
ModifierGate::NON_NEGATIVE,
));
assert!(
text.contains("NumberOutOfRange: retry duration must be non-negative"),
"{text}"
);
let text = rejection(check_modifier_literal(
&placeholder("__AUTO_0__"),
&TX_BATCH_SIZE,
ModifierGate::POSITIVE,
));
assert!(
text.contains("InvalidArgument: batch size must be a positive integer"),
"{text}"
);
for gate in [ModifierGate::POSITIVE, ModifierGate::NON_NEGATIVE] {
check_modifier_literal(&placeholder("__AUTO_1__"), &TX_BATCH_SIZE, gate)
.expect("a valid placeholder passes");
}
check_modifier_literal(&placeholder("n"), &TX_BATCH_SIZE, ModifierGate::POSITIVE)
.expect("a caller parameter passes");
}
}