use super::{
NixLibrary, OverlayRef, PackageRef,
raw::{AsNixValue, NixRepresentation, NixValue},
};
use crate::{
ConfigValue, Expr, IntoRusixValue, RusixValue, ValidationError,
ir::{IntoNode, Node, Origin},
sealed,
};
use std::marker::PhantomData;
pub trait NixExpression: NixRepresentation + Clone + IntoRusixValue {
#[track_caller]
fn bind<R: NixExpression>(self, build: impl FnOnce(Self) -> R) -> R {
R::from_expression(
NixValue::function(|parameter| build(Self::from_expression(parameter)).as_expression())
.call(self.as_expression()),
)
}
#[track_caller]
fn try_bind_record<R: NixExpression>(
record: impl IntoRusixValue,
build: impl FnOnce(Self) -> R,
) -> Result<R, ValidationError> {
Ok(Self::from_expression(record.try_into_nix_value()?).bind(build))
}
#[track_caller]
fn choose(condition: impl Into<Expr<bool>>, yes: Self, no: Self) -> Self {
Self::from_expression(NixValue::if_else(
condition.into(),
yes.as_expression(),
no.as_expression(),
))
}
#[track_caller]
fn require(
self,
lib: &NixLibrary,
condition: impl Into<Expr<bool>>,
message: impl Into<Expr<String>>,
) -> Self {
lib.throw_if_not(condition, message, self)
}
#[track_caller]
fn asserted(self, condition: impl Into<Expr<bool>>) -> Self {
Self::from_expression(NixValue::assert(condition.into(), self.as_expression()))
}
}
impl<T: NixRepresentation + Clone + IntoRusixValue> NixExpression for T {}
impl NixRepresentation for NixValue {
fn from_expression(value: NixValue) -> Self {
value
}
fn as_expression(&self) -> NixValue {
self.clone()
}
}
macro_rules! scalar {
($ty:ty) => {
impl NixRepresentation for Expr<$ty> {
fn from_expression(value: NixValue) -> Self {
value.into_expr()
}
fn as_expression(&self) -> NixValue {
self.clone().into()
}
}
impl From<$ty> for Expr<$ty> {
#[track_caller]
fn from(value: $ty) -> Self {
NixValue::from(value).into_expr()
}
}
};
}
scalar!(bool);
scalar!(String);
scalar!(i64);
impl From<&str> for Expr<String> {
#[track_caller]
fn from(value: &str) -> Self {
NixValue::from(value).into_expr()
}
}
impl Expr<String> {
#[track_caller]
pub fn concat(parts: impl IntoIterator<Item = Self>) -> Self {
NixValue::concat_text(parts.into_iter().map(|part| part.as_expression())).into_expr()
}
}
macro_rules! expression_handle {
($name:ident $(<$($parameter:ident),+>)?) => {
impl$(<$($parameter: NixExpression),+>)? sealed::Sealed for $name$(<$($parameter),+>)? {}
impl$(<$($parameter: NixExpression),+>)? ConfigValue for $name$(<$($parameter),+>)? {}
impl$(<$($parameter: NixExpression),+>)? IntoNode for $name$(<$($parameter),+>)? {
fn into_node(self, origin: Origin) -> Node {
self.value.into_node(origin)
}
}
impl$(<$($parameter: NixExpression),+>)? IntoRusixValue for $name$(<$($parameter),+>)? {
#[track_caller]
fn into_value(self) -> RusixValue {
RusixValue::leaf(self)
}
}
impl$(<$($parameter: NixExpression),+>)? NixRepresentation for $name$(<$($parameter),+>)? {
fn from_expression(value: NixValue) -> Self {
Self { value, $(_type: PhantomData::<($($parameter,)+)>,)? }
}
fn as_expression(&self) -> NixValue {
self.value.clone()
}
}
impl$(<$($parameter: NixExpression),+>)? From<$name$(<$($parameter),+>)?> for NixValue {
fn from(value: $name$(<$($parameter),+>)?) -> Self {
value.value
}
}
};
}
pub trait IntoNixExpression {
type Expression: NixExpression;
#[track_caller]
fn into_expression(self) -> Self::Expression;
}
impl<T: NixExpression> IntoNixExpression for T {
type Expression = T;
fn into_expression(self) -> T {
self
}
}
macro_rules! expression_literal {
($ty:ty, $expression:ty) => {
impl IntoNixExpression for $ty {
type Expression = $expression;
#[track_caller]
fn into_expression(self) -> Self::Expression {
self.into()
}
}
};
}
expression_literal!(bool, Expr<bool>);
expression_literal!(i64, Expr<i64>);
expression_literal!(String, Expr<String>);
expression_literal!(&str, Expr<String>);
expression_literal!(PackageRef, Package);
pub trait NixOverridable: NixExpression {
#[track_caller]
fn override_arguments(&self, arguments: impl ConfigValue) -> Self {
Self::from_expression(
self.as_expression()
.override_args(NixValue::literal(arguments)),
)
}
}
#[derive(Clone, Debug)]
pub struct Package {
value: NixValue,
}
expression_handle!(Package);
impl From<PackageRef> for Package {
fn from(reference: PackageRef) -> Self {
Self::from_expression(reference.as_value())
}
}
impl NixOverridable for Package {}
impl Package {
#[track_caller]
pub fn view<V: NixExpression>(&self) -> V {
V::from_expression(self.value.clone())
}
#[track_caller]
pub fn output(&self, name: &str) -> Self {
Self::from_expression(self.value.clone().select_segments([name]))
}
#[track_caller]
pub fn field<T: NixExpression>(&self, name: &str) -> T {
T::from_expression(self.value.clone().select(name))
}
#[track_caller]
pub fn override_arguments(&self, arguments: impl ConfigValue) -> Self {
NixOverridable::override_arguments(self, arguments)
}
#[track_caller]
pub fn try_override_arguments(
&self,
arguments: impl IntoRusixValue,
) -> Result<Self, ValidationError> {
Ok(self.override_arguments(arguments.try_into_nix_value()?))
}
#[track_caller]
pub fn override_attrs(&self, update: impl FnOnce(NixAttrs) -> NixAttrs) -> Self {
Self::from_expression(
self.value
.clone()
.override_attrs(NixCallable::from_function(update)),
)
}
#[track_caller]
pub fn try_override_attrs<A: NixExpression, V: IntoRusixValue>(
&self,
update: impl FnOnce(A) -> V,
) -> Result<Self, ValidationError> {
let update = NixCallable::<NixAttrs, A>::try_from_function(update)?;
Ok(Self::from_expression(
self.value.clone().override_attrs(update),
))
}
#[track_caller]
pub fn extend(&self, attributes: NixAttrs) -> Self {
Self::from_expression(self.value.clone().merge_attrs(attributes))
}
}
#[derive(Clone, Debug)]
pub struct Overlay {
value: NixValue,
}
expression_handle!(Overlay);
impl From<OverlayRef> for Overlay {
fn from(reference: OverlayRef) -> Self {
Self::from_expression(reference.as_value())
}
}
impl Overlay {
#[track_caller]
pub fn try_from_function<F: NixExpression, P: NixExpression, V: IntoRusixValue>(
build: impl FnOnce(F, P) -> V,
) -> Result<Self, ValidationError> {
let mut error = None;
let function = NixValue::function(|final_pkgs| {
match NixCallable::<NixAttrs, P>::try_from_function(|prev_pkgs| {
build(F::from_expression(final_pkgs), prev_pkgs)
}) {
Ok(function) => function.as_expression(),
Err(failure) => {
error = Some(failure);
NixValue::null()
}
}
});
match error {
Some(error) => Err(error),
None => Ok(Self::from_expression(function)),
}
}
#[track_caller]
pub fn from_function(build: impl FnOnce(NixAttrs, NixAttrs) -> NixAttrs) -> Self {
Self::from_expression(NixValue::function(|final_pkgs| {
NixValue::function(|prev_pkgs| {
build(
NixAttrs::from_expression(final_pkgs),
NixAttrs::from_expression(prev_pkgs),
)
.as_expression()
})
}))
}
}
#[derive(Clone, Debug)]
pub struct Overridable<T: NixExpression> {
value: NixValue,
_type: PhantomData<(T,)>,
}
expression_handle!(Overridable<T>);
impl<T: NixExpression> NixOverridable for Overridable<T> {}
impl<T: NixExpression> Overridable<T> {
pub fn inner(&self) -> T {
T::from_expression(self.value.clone())
}
#[track_caller]
pub fn extend(&self, attributes: NixAttrs) -> Self {
Self::from_expression(self.value.clone().merge_attrs(attributes))
}
}
impl<R: NixExpression, A: NixExpression> Overridable<NixCallable<R, A>> {
#[track_caller]
pub fn call(&self, argument: impl Into<A>) -> R {
self.inner().call(argument)
}
}
impl<R: NixExpression> Overridable<NixCallable<R>> {
#[track_caller]
pub fn try_call(&self, argument: impl IntoRusixValue) -> Result<R, ValidationError> {
self.inner().try_call(argument)
}
}
#[derive(Clone, Debug)]
pub struct NixCallable<R: NixExpression = NixValue, A: NixExpression = NixValue> {
value: NixValue,
_type: PhantomData<(R, A)>,
}
expression_handle!(NixCallable<R, A>);
impl<R: NixExpression, A: NixExpression> NixCallable<R, A> {
#[track_caller]
pub fn from_function(build: impl FnOnce(A) -> R) -> Self {
Self::from_expression(NixValue::function(|parameter| {
build(A::from_expression(parameter)).as_expression()
}))
}
#[track_caller]
pub fn try_from_function<V: IntoRusixValue>(
build: impl FnOnce(A) -> V,
) -> Result<Self, ValidationError> {
let mut error = None;
let function = NixValue::function(|parameter| {
match build(A::from_expression(parameter)).try_into_nix_value() {
Ok(body) => body,
Err(failure) => {
error = Some(failure);
NixValue::null()
}
}
});
match error {
Some(error) => Err(error),
None => Ok(Self::from_expression(function)),
}
}
#[track_caller]
pub fn call(&self, argument: impl Into<A>) -> R {
R::from_expression(self.value.clone().call(argument.into().as_expression()))
}
}
impl<R: NixExpression> NixCallable<R> {
#[track_caller]
pub fn try_call(&self, argument: impl IntoRusixValue) -> Result<R, ValidationError> {
Ok(self.call(argument.try_into_nix_value()?))
}
}
#[derive(Clone, Debug)]
pub struct NixAttrs<T: NixExpression = NixValue> {
value: NixValue,
_type: PhantomData<(T,)>,
}
expression_handle!(NixAttrs<T>);
impl<T: NixExpression> NixAttrs<T> {
#[track_caller]
pub fn new(fields: impl IntoIterator<Item = (impl Into<String>, T)>) -> Self {
Self::from_expression(NixValue::record(
fields
.into_iter()
.map(|(key, value)| (key, value.as_expression())),
))
}
#[track_caller]
pub fn get(&self, name: &str) -> T {
T::from_expression(self.value.clone().select_segments([name]))
}
#[track_caller]
pub fn has(&self, name: &str) -> Expr<bool> {
self.value.clone().has_attr(name).into_expr()
}
#[track_caller]
pub fn get_or(&self, name: &str, fallback: impl Into<T>) -> T {
T::from_expression(
self.value
.clone()
.attr_or(name, fallback.into().as_expression()),
)
}
#[track_caller]
pub fn get_optional(&self, name: &str) -> NixNullable<T> {
NixNullable::from_expression(self.value.clone().attr_or(name, NixValue::null()))
}
#[track_caller]
pub fn merge(self, right: Self) -> Self {
Self::from_expression(self.value.merge_attrs(right))
}
}
impl NixAttrs {
#[track_caller]
pub fn try_from_record(record: impl IntoRusixValue) -> Result<Self, ValidationError> {
Ok(Self::from_expression(record.try_into_nix_value()?))
}
#[track_caller]
pub fn field<T: NixExpression>(&self, name: &str) -> T {
T::from_expression(self.get(name))
}
}
#[derive(Clone, Debug)]
pub struct NixList<T: NixExpression> {
value: NixValue,
_type: PhantomData<(T,)>,
}
expression_handle!(NixList<T>);
impl<T: NixExpression> NixList<T> {
#[track_caller]
pub fn new(items: impl IntoIterator<Item = T>) -> Self {
Self::from_expression(NixValue::list(
items.into_iter().map(|item| item.as_expression()),
))
}
#[track_caller]
pub fn concat(lists: impl IntoIterator<Item = Self>) -> Self {
Self::from_expression(NixValue::concat_lists(
lists.into_iter().map(|list| list.as_expression()),
))
}
#[track_caller]
pub fn concat_with(lib: &NixLibrary, lists: impl IntoIterator<Item = Self>) -> Self {
lib.concat_lists(lists)
}
#[track_caller]
pub fn optional(lib: &NixLibrary, condition: impl Into<Expr<bool>>, value: T) -> Self {
lib.optional(condition, value)
}
#[track_caller]
pub fn when(self, lib: &NixLibrary, condition: impl Into<Expr<bool>>) -> Self {
lib.optionals(condition, self)
}
}
#[derive(Clone, Debug)]
pub struct NixPath {
value: NixValue,
}
expression_handle!(NixPath);
impl super::ToNixText for NixPath {
#[track_caller]
fn to_nix_text(self) -> Expr<String> {
self.value.to_text().into_expr()
}
}
#[derive(Clone, Debug)]
pub struct NixNullable<T: NixExpression> {
value: NixValue,
_type: PhantomData<(T,)>,
}
expression_handle!(NixNullable<T>);
impl<T: NixExpression> NixNullable<T> {
#[track_caller]
pub fn null() -> Self {
Self::from_expression(NixValue::null())
}
#[track_caller]
pub fn some(value: impl Into<T>) -> Self {
Self::from_expression(value.into().as_expression())
}
#[track_caller]
pub fn is_null(&self) -> Expr<bool> {
self.value.clone().equals(NixValue::null()).into_expr()
}
#[track_caller]
pub fn unwrap_or(self, fallback: impl Into<T>) -> T {
self.bind(|value| {
T::choose(
value.is_null(),
fallback.into(),
T::from_expression(value.value),
)
})
}
#[track_caller]
pub fn map<U: NixExpression>(self, transform: impl FnOnce(T) -> U) -> NixNullable<U> {
self.bind(|value| {
NixNullable::choose(
value.is_null(),
NixNullable::null(),
NixNullable::some(transform(T::from_expression(value.value))),
)
})
}
}
#[derive(Clone, Debug)]
pub struct Stdenv {
value: NixValue,
}
expression_handle!(Stdenv);
impl Stdenv {
#[track_caller]
pub fn mk_derivation(&self, attributes: impl ConfigValue) -> Package {
self.builder().call(NixValue::literal(attributes))
}
#[track_caller]
pub fn try_mk_derivation(
&self,
attributes: impl IntoRusixValue,
) -> Result<Package, ValidationError> {
self.builder().try_call(attributes)
}
#[track_caller]
pub fn builder(&self) -> NixCallable<Package> {
NixCallable::from_expression(self.value.clone().select("mkDerivation"))
}
#[track_caller]
pub fn host_platform(&self) -> super::Platform {
super::Platform::from_expression(self.value.clone().select("hostPlatform"))
}
#[track_caller]
pub fn build_platform(&self) -> super::Platform {
super::Platform::from_expression(self.value.clone().select("buildPlatform"))
}
#[track_caller]
pub fn target_platform(&self) -> super::Platform {
super::Platform::from_expression(self.value.clone().select("targetPlatform"))
}
#[track_caller]
pub fn build_host_equal(&self) -> Expr<bool> {
crate::package::build_host_equal(self.value.clone())
}
}
impl NixRepresentation for NixLibrary {
fn from_expression(value: NixValue) -> Self {
Self::from_value(value)
}
fn as_expression(&self) -> NixValue {
self.value.clone()
}
}
impl IntoRusixValue for NixLibrary {
#[track_caller]
fn into_value(self) -> RusixValue {
RusixValue::leaf(self.as_expression())
}
}
impl sealed::Sealed for NixLibrary {}
impl ConfigValue for NixLibrary {}
impl IntoNode for NixLibrary {
fn into_node(self, origin: Origin) -> Node {
self.as_expression().into_node(origin)
}
}
impl Expr<String> {
#[track_caller]
pub fn when(self, lib: &NixLibrary, condition: impl Into<Expr<bool>>) -> Self {
lib.optional_text(condition.into(), self)
}
}
impl From<NixLibrary> for NixValue {
fn from(value: NixLibrary) -> Self {
value.as_expression()
}
}