use super::{ModuleRef, NixCallable, NixExpression, NixFunction, Nixpkgs, OverlayRef, PackageRef};
use crate::ir::{Reference, Source};
use crate::{
ConfigValue, ValidationError,
ir::{IntoNode, Node, Origin, ValueKind},
sealed,
};
pub trait NixRepresentation {
fn from_expression(value: NixValue) -> Self;
fn as_expression(&self) -> NixValue;
}
pub fn expect<T: super::NixExpression>(value: NixValue) -> T {
T::from_expression(value)
}
#[derive(Clone, Debug)]
pub struct AttrPath(
pub(crate) Vec<String>,
);
impl AttrPath {
pub fn dotted(path: &str) -> Self {
Self(path.split('.').map(str::to_owned).collect())
}
pub fn segments(parts: impl IntoIterator<Item = impl Into<String>>) -> Self {
Self(parts.into_iter().map(Into::into).collect())
}
pub fn parts(&self) -> &[String] {
&self.0
}
pub(crate) fn validate(&self, origin: &Origin) -> Result<(), ValidationError> {
if self.0.is_empty() || self.0.iter().any(|p| p.is_empty() || p.contains('\0')) {
return Err(ValidationError {
origin: origin.clone(),
message: "Nix attribute paths need nonempty, NUL-free segments".into(),
});
}
Ok(())
}
}
#[derive(Clone, Debug)]
pub struct NixValue(
pub(crate) Node,
);
impl sealed::Sealed for NixValue {}
impl ConfigValue for NixValue {}
impl IntoNode for NixValue {
fn into_node(self, _: Origin) -> Node {
self.0
}
}
impl NixValue {
pub(crate) fn from_node(node: Node) -> Self {
Self(node)
}
#[track_caller]
pub fn builtin(name: &str) -> Self {
Self(
Reference {
source: Source::Builtins,
path: Some(AttrPath::segments([name])),
origin: Origin::caller(format!("Nix builtin lookup {name}")),
}
.node(),
)
}
#[track_caller]
pub fn merge_attrs(self, right: impl Into<Self>) -> Self {
Self(Node {
origin: Origin::caller("Nix attribute-set union"),
kind: ValueKind::AttrMerge(Box::new(self.0), Box::new(right.into().0)),
})
}
#[track_caller]
pub fn assert(condition: impl Into<Self>, value: impl Into<Self>) -> Self {
Self(Node {
origin: Origin::caller("Nix expression assertion"),
kind: ValueKind::Assert(Box::new(condition.into().0), Box::new(value.into().0)),
})
}
#[track_caller]
pub fn function(build: impl FnOnce(Self) -> Self) -> Self {
let origin = Origin::caller("opaque Nix callback");
let (binding, parameter) = Self::parameter(&origin);
Self(Node {
origin,
kind: ValueKind::Function {
binding,
body: Box::new(build(parameter).0),
},
})
}
fn parameter(origin: &Origin) -> (u64, Self) {
use std::sync::atomic::{AtomicU64, Ordering};
static NEXT: AtomicU64 = AtomicU64::new(0);
let binding = NEXT.fetch_add(1, Ordering::Relaxed);
let parameter = Self(Node {
origin: origin.clone(),
kind: ValueKind::Parameter(binding),
});
(binding, parameter)
}
#[track_caller]
pub fn function_attrs<K: Into<String>>(
arguments: impl IntoIterator<Item = impl Into<String>>,
build: impl FnOnce(Self) -> (Vec<(K, Self)>, Self),
) -> Self {
let origin = Origin::caller("Nix argument-set function");
let (binding, parameter) = Self::parameter(&origin);
let (defaults, body) = build(parameter);
Self(Node {
origin,
kind: ValueKind::FunctionAttrs {
binding,
arguments: arguments.into_iter().map(Into::into).collect(),
defaults: defaults
.into_iter()
.map(|(name, value)| (name.into(), value.0))
.collect(),
body: Box::new(body.0),
},
})
}
#[track_caller]
pub fn if_else(condition: impl Into<Self>, yes: impl Into<Self>, no: impl Into<Self>) -> Self {
Self(Node {
origin: Origin::caller("opaque Nix choice"),
kind: ValueKind::If(
Box::new(condition.into().0),
Box::new(yes.into().0),
Box::new(no.into().0),
),
})
}
#[track_caller]
pub fn and(self, other: impl Into<Self>) -> Self {
self.into_expr::<bool>()
.and(other.into().into_expr::<bool>())
.into()
}
#[track_caller]
pub fn or(self, other: impl Into<Self>) -> Self {
self.into_expr::<bool>()
.or(other.into().into_expr::<bool>())
.into()
}
#[track_caller]
pub fn implies(self, other: impl Into<Self>) -> Self {
self.into_expr::<bool>()
.implies(other.into().into_expr::<bool>())
.into()
}
#[track_caller]
pub fn equals(self, other: impl Into<Self>) -> Self {
Self(Node {
origin: Origin::caller("opaque Nix equality"),
kind: ValueKind::Equal(Box::new(self.0), Box::new(other.into().0)),
})
}
#[track_caller]
pub fn to_text(self) -> Self {
Self(Node {
origin: Origin::caller("opaque Nix to text"),
kind: ValueKind::ToText(Box::new(self.0)),
})
}
#[track_caller]
pub fn literal(value: impl ConfigValue) -> Self {
Self(value.into_node(Origin::caller("opaque call argument")))
}
#[track_caller]
pub fn null() -> Self {
Self(Node {
origin: Origin::caller("opaque Nix null"),
kind: ValueKind::Null,
})
}
#[track_caller]
pub fn record(fields: impl IntoIterator<Item = (impl Into<String>, Self)>) -> Self {
Self(Node {
origin: Origin::caller("opaque Nix record"),
kind: ValueKind::OpaqueRecord(
fields
.into_iter()
.map(|(key, value)| (key.into(), value.0))
.collect(),
),
})
}
#[track_caller]
pub fn list(items: impl IntoIterator<Item = Self>) -> Self {
Self(Node {
origin: Origin::caller("opaque Nix list"),
kind: ValueKind::List(items.into_iter().map(|value| value.0).collect()),
})
}
#[track_caller]
pub fn concat_lists(lists: impl IntoIterator<Item = Self>) -> Self {
Self::builtin("concatLists").call(Self::list(lists))
}
#[track_caller]
pub fn call(self, argument: impl ConfigValue) -> Self {
let origin = Origin::caller("opaque Nix function call");
Self(Node {
origin: origin.clone(),
kind: ValueKind::Apply(Box::new(self.0), Box::new(argument.into_node(origin))),
})
}
#[track_caller]
pub fn apply(mut self, arguments: impl IntoIterator<Item = Self>) -> Self {
for argument in arguments {
self = self.call(argument);
}
self
}
#[track_caller]
pub fn join_text(separator: &str, parts: Self) -> Self {
Nixpkgs::new()
.function("concatStringsSep")
.apply([separator.into(), parts])
}
#[track_caller]
pub fn concat_text(parts: impl IntoIterator<Item = Self>) -> Self {
Self::join_text("", Self::list(parts))
}
#[track_caller]
pub fn replace_text(
self,
replacements: impl IntoIterator<Item = (impl Into<Self>, impl Into<Self>)>,
) -> Self {
let [from, to] = replacement_lists(replacements);
Self::builtin("replaceStrings").apply([from, to, self])
}
#[track_caller]
pub fn has_attr(self, name: impl Into<Self>) -> Self {
Self::builtin("hasAttr").apply([name.into(), self])
}
#[track_caller]
pub fn attr_or(self, name: impl Into<Self>, fallback: impl Into<Self>) -> Self {
let name = name.into();
let fallback = fallback.into();
let origin = Origin::caller("opaque Nix attribute fallback");
let (attrs_binding, attrs) = Self::parameter(&origin);
let (name_binding, attribute_name) = Self::parameter(&origin);
let selected = Self::if_else(
attrs.clone().has_attr(attribute_name.clone()),
Self::builtin("getAttr").apply([attribute_name, attrs]),
fallback,
);
let lookup = Self(Node {
origin: origin.clone(),
kind: ValueKind::Function {
binding: name_binding,
body: Box::new(selected.0),
},
});
Self(Node {
origin,
kind: ValueKind::Function {
binding: attrs_binding,
body: Box::new(lookup.call(name).0),
},
})
.call(self)
}
#[track_caller]
pub fn override_args(self, overrides: impl Into<Self>) -> Self {
self.select("override").call(overrides.into())
}
#[track_caller]
pub fn override_attrs(self, update: impl Into<Self>) -> Self {
self.select("overrideAttrs").call(update.into())
}
#[track_caller]
pub fn select(self, path: &str) -> Self {
self.select_segments(path.split('.'))
}
#[track_caller]
pub fn select_segments(self, parts: impl IntoIterator<Item = impl Into<String>>) -> Self {
let path = AttrPath::segments(parts);
Self(Node {
origin: Origin::caller(format!("opaque Nix selection {}", path.parts().join("."))),
kind: ValueKind::Select(Box::new(self.0), path),
})
}
pub fn into_expr<T>(self) -> crate::Expr<T>
where
crate::Expr<T>: ConfigValue,
{
crate::Expr::new(self.0.kind, self.0.origin)
}
}
#[track_caller]
pub(super) fn replacement_lists(
replacements: impl IntoIterator<Item = (impl Into<NixValue>, impl Into<NixValue>)>,
) -> [NixValue; 2] {
let mut from = Vec::new();
let mut to = Vec::new();
for (pattern, replacement) in replacements {
from.push(pattern.into());
to.push(replacement.into());
}
[NixValue::list(from), NixValue::list(to)]
}
impl std::ops::Not for NixValue {
type Output = Self;
#[track_caller]
fn not(self) -> Self {
Self::if_else(self, false, true)
}
}
macro_rules! literal_conversion {
($($ty:ty),* $(,)?) => { $(
impl From<$ty> for NixValue {
#[track_caller]
fn from(value: $ty) -> Self { Self::literal(value) }
}
)* };
}
literal_conversion!(
bool,
i32,
i64,
u16,
f64,
String,
&str,
crate::Expr<bool>,
crate::Expr<i64>,
crate::Expr<String>
);
macro_rules! reference_conversion {
($($ty:ty),* $(,)?) => { $(
impl From<$ty> for NixValue {
fn from(value: $ty) -> Self { value.as_value() }
}
)* };
}
reference_conversion!(PackageRef, ModuleRef, NixFunction, OverlayRef);
impl<T: Into<NixValue>> From<Option<T>> for NixValue {
#[track_caller]
fn from(value: Option<T>) -> Self {
match value {
Some(value) => value.into(),
None => Self::null(),
}
}
}
impl From<std::collections::BTreeMap<String, NixValue>> for NixValue {
#[track_caller]
fn from(value: std::collections::BTreeMap<String, NixValue>) -> Self {
Self::record(value)
}
}
pub trait AsNixValue {
fn as_value(&self) -> NixValue;
}
pub trait NixFunctionExt: AsNixValue {
fn returning<R: NixExpression>(&self) -> NixCallable<R> {
NixCallable::from_expression(self.as_value())
}
#[track_caller]
fn signature<A: NixExpression, R: NixExpression>(&self) -> NixCallable<R, A> {
NixCallable::from_expression(self.as_value())
}
#[track_caller]
fn call(&self, argument: impl ConfigValue) -> NixValue {
self.as_value().call(argument)
}
#[track_caller]
fn apply(&self, arguments: impl IntoIterator<Item = NixValue>) -> NixValue {
self.as_value().apply(arguments)
}
}
impl NixFunctionExt for NixFunction {}
pub trait NixpkgsExt {
#[track_caller]
fn value(&self, path: &str) -> NixValue;
#[track_caller]
fn as_value(&self) -> NixValue;
#[track_caller]
fn lib_value(&self, path: &str) -> NixValue;
}
impl NixpkgsExt for Nixpkgs {
#[track_caller]
fn value(&self, path: &str) -> NixValue {
NixValue(
Reference {
source: self.package_source(),
path: Some(AttrPath::dotted(path)),
origin: Origin::caller(format!("nixpkgs value lookup {path}")),
}
.node(),
)
}
#[track_caller]
fn as_value(&self) -> NixValue {
NixValue(
Reference {
source: self.package_source(),
path: None,
origin: Origin::caller("nixpkgs package set"),
}
.node(),
)
}
#[track_caller]
fn lib_value(&self, path: &str) -> NixValue {
NixValue(
Reference {
source: Source::Library,
path: Some(AttrPath::dotted(path)),
origin: Origin::caller(format!("nixpkgs lib value lookup {path}")),
}
.node(),
)
}
}
pub trait InputRefExt {
#[track_caller]
fn value(&self, path: &str) -> NixValue;
}
impl InputRefExt for super::InputRef {
#[track_caller]
fn value(&self, path: &str) -> NixValue {
NixValue(self.lookup(path, "value").node())
}
}