use crate::ir::validation::reject_nul;
use crate::ir::{Assignment, IntoNode, Node, Origin, ValueKind};
use crate::{interop, ir};
use std::marker::PhantomData;
#[derive(Clone, Debug)]
pub struct Expr<T> {
node: Node,
ty: PhantomData<T>,
}
impl<T> Expr<T> {
pub(crate) fn new(kind: ValueKind, origin: Origin) -> Self {
Self {
node: Node { origin, kind },
ty: PhantomData,
}
}
}
impl Expr<i64> {
#[track_caller]
pub fn to_text(self) -> Expr<String> {
Expr::new(
ValueKind::ToText(Box::new(self.node)),
Origin::caller("integer to text"),
)
}
#[track_caller]
pub fn int(value: i64) -> Self {
Self::new(ValueKind::Int(value), Origin::caller("integer literal"))
}
#[track_caller]
pub fn divide(self, denominator: Self) -> Self {
Self::new(
ValueKind::Divide(Box::new(self.node), Box::new(denominator.node)),
Origin::caller("integer division"),
)
}
#[track_caller]
pub fn in_range(self, min: i64, max: i64, message: impl Into<String>) -> Self {
Self::new(
ValueKind::InRange {
value: Box::new(self.node),
min,
max,
message: message.into(),
},
Origin::caller("integer range constraint"),
)
}
}
impl Expr<String> {
#[track_caller]
pub fn with_prefix(self, prefix: impl Into<String>) -> Self {
Self::new(
ValueKind::StringPrefix {
prefix: prefix.into(),
value: Box::new(self.node),
},
Origin::caller("symbolic string prefix"),
)
}
}
impl Expr<bool> {
#[track_caller]
pub fn boolean(value: bool) -> Self {
Self::new(ValueKind::Bool(value), Origin::caller("boolean literal"))
}
#[track_caller]
pub fn and(self, other: Self) -> Self {
let other = interop::raw::NixValue::if_else(other, true, false);
interop::raw::NixValue::if_else(self, other, false).into_expr()
}
#[track_caller]
pub fn or(self, other: Self) -> Self {
let other = interop::raw::NixValue::if_else(other, true, false);
interop::raw::NixValue::if_else(self, true, other).into_expr()
}
#[track_caller]
pub fn implies(self, other: Self) -> Self {
(!self).or(other)
}
}
impl std::ops::Not for Expr<bool> {
type Output = Self;
#[track_caller]
fn not(self) -> Self {
(!interop::raw::NixValue::from(self)).into_expr()
}
}
pub(crate) mod sealed {
pub trait Sealed {}
}
pub trait ConfigValue: sealed::Sealed + ir::IntoNode {}
macro_rules! primitive {
($ty:ty, $variant:ident) => {
impl sealed::Sealed for $ty {}
impl ConfigValue for $ty {}
impl IntoNode for $ty {
fn into_node(self, origin: Origin) -> Node {
Node {
origin,
kind: ValueKind::$variant(self.into()),
}
}
}
};
}
primitive!(bool, Bool);
primitive!(i32, Int);
primitive!(i64, Int);
primitive!(u16, Int);
primitive!(f64, Float);
primitive!(String, String);
primitive!(&str, String);
impl<T: ConfigValue> sealed::Sealed for Vec<T> {}
impl<T: ConfigValue> ConfigValue for Vec<T> {}
impl<T: ConfigValue> IntoNode for Vec<T> {
fn into_node(self, origin: Origin) -> Node {
let children = self
.into_iter()
.enumerate()
.map(|(i, value)| {
let child = Origin::new(
&origin.file,
origin.line,
origin.column,
format!("{}[{i}]", origin.purpose),
);
value.into_node(child)
})
.collect();
Node {
origin,
kind: ValueKind::List(children),
}
}
}
macro_rules! expression_value {
($ty:ty) => {
impl sealed::Sealed for Expr<$ty> {}
impl ConfigValue for Expr<$ty> {}
impl IntoNode for Expr<$ty> {
fn into_node(self, _: Origin) -> Node {
self.node
}
}
};
}
expression_value!(i64);
expression_value!(bool);
expression_value!(String);
#[derive(Clone, Debug)]
pub struct Config {
pub origin: Origin,
pub assignments: Vec<Assignment>,
pub(crate) error: Option<ValidationError>,
}
pub trait IntoConfig {
#[track_caller]
fn into_config(self) -> Config;
}
impl IntoConfig for Config {
fn into_config(self) -> Config {
self
}
}
impl IntoConfig for &Config {
fn into_config(self) -> Config {
self.clone()
}
}
impl Config {
#[track_caller]
pub fn new() -> Self {
Self {
origin: Origin::caller("configuration"),
assignments: Vec::new(),
error: None,
}
}
#[track_caller]
pub fn set_dynamic(mut self, path: impl Into<String>, value: impl ConfigValue) -> Self {
let path = path.into();
let origin = Origin::caller(format!("set {path}"));
let value_origin = Origin::caller(format!("value of {path}"));
self.assignments.push(Assignment {
origin,
segments: path.split('.').map(str::to_owned).collect(),
path,
value: value.into_node(value_origin),
});
self
}
pub fn validate(&self) -> Result<(), ValidationError> {
if let Some(error) = &self.error {
return Err(error.clone());
}
let mut seen: Vec<&[String]> = Vec::new();
for assignment in &self.assignments {
let path = &assignment.path;
reject_nul(path, &assignment.origin)?;
let parts = assignment.path_segments();
if parts.is_empty()
|| parts
.iter()
.any(|part| part.is_empty() || part.contains('\0'))
{
return Err(ValidationError {
origin: assignment.origin.clone(),
message: "option paths must have nonempty dot-separated segments".into(),
});
}
if seen
.iter()
.any(|old| parts.starts_with(old) || old.starts_with(parts))
{
return Err(ValidationError {
origin: assignment.origin.clone(),
message: format!("duplicate or conflicting option path: {path}"),
});
}
seen.push(parts);
assignment.value.validate()?;
}
Ok(())
}
}
impl Default for Config {
#[track_caller]
fn default() -> Self {
Self::new()
}
}
#[derive(Clone, Debug)]
pub struct ValidationError {
pub origin: Origin,
pub message: String,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn caller_and_ids_are_deterministic() {
fn make() -> Config {
Config::new().set_dynamic("a", true)
}
let first = make();
let second = make();
assert_eq!(first.assignments[0].origin, second.assignments[0].origin);
assert_eq!(first.assignments[0].origin.file, file!());
assert_ne!(first.origin.id, first.assignments[0].origin.id);
}
#[test]
fn paths_are_validated_in_both_prefix_directions() {
for paths in [["a", "a"], ["a", "a.b"], ["a.b", "a"], ["a..b", "x"]] {
assert!(
Config::new()
.set_dynamic(paths[0], true)
.set_dynamic(paths[1], 1)
.validate()
.is_err()
);
}
assert!(
Config::new()
.set_dynamic("a.b", true)
.set_dynamic("a.c", vec![22])
.validate()
.is_ok()
);
}
#[test]
fn unsupported_nul_is_rejected_at_its_origin() {
let config = Config::new().set_dynamic("strings", vec!["valid", "bad\0string"]);
let error = config.validate().unwrap_err();
let ValueKind::List(items) = &config.assignments[0].value.kind else {
panic!()
};
assert_eq!(error.origin, items[1].origin);
assert!(
Config::new()
.set_dynamic("bad\0path", true)
.validate()
.is_err()
);
assert!(
Config::new()
.set_dynamic("number", Expr::int(1).in_range(0, 2, "bad\0message"))
.validate()
.is_err()
);
}
}