use crate::{
ConfigValue, ValidationError,
ir::{IntoNode, Node, Origin, Reference, Source},
sealed,
};
use std::path::PathBuf;
pub mod raw;
use raw::{AttrPath, NixFunctionExt, NixRepresentation, NixValue};
mod library;
mod records;
pub use records::{FinalAttrs, Platform};
mod typed;
mod text;
pub use text::ToNixText;
pub use library::NixLibrary;
pub use typed::{
IntoNixExpression, NixAttrs, NixCallable, NixExpression, NixList, NixNullable, NixOverridable,
NixPath, Overlay, Overridable, Package, Stdenv,
};
macro_rules! handle {
($name:ident, $docs:literal) => {
#[doc = $docs]
#[derive(Clone, Debug)]
pub struct $name(
/// Source, literal lookup path and Rust location for the object Nix resolves later.
pub(crate) Reference,
);
impl crate::ir::ReferencedExpression for $name {
fn reference(&self) -> &Reference {
&self.0
}
}
impl raw::AsNixValue for $name {
fn as_value(&self) -> NixValue {
NixValue(self.0.node())
}
}
};
}
handle!(
PackageRef,
"A reference to a package that Nix will look up later.
In nixpkgs, a package describes how to build software and where its outputs will
be stored. This handle can be passed to package-specific APIs such as
[`crate::nixos::NixosModule::system_packages`] without building the package.
Rust distinguishes it from a module handle; NixOS checks whether the referenced
value really is a package. The lookup records its Rust source location."
);
handle!(
ModuleRef,
"A reference to an existing NixOS configuration module.
A NixOS module contributes settings or declares configurable options for a
system; NixOS combines it with other modules. Import this handle with
[`crate::nixos::NixosModule::import_ref`]. Nix evaluates the module’s contents,
and Rusix records the Rust import location for errors in external Nix code."
);
handle!(
NixFunction,
"A reference to a Nix function that Rust can describe calls to.
Use it to reuse existing nixpkgs helpers or functions from a local Nix file.
[`raw::NixFunctionExt::call`] passes one argument;
[`raw::NixFunctionExt::apply`] passes arguments one at a
time, as Nix functions commonly require. Neither executes the function in Rust.
Nix checks the arguments, and the result is a [`NixValue`]; Rusix does not
infer that a function returns a package or module."
);
#[derive(Clone, Debug)]
pub struct PackageFunction<R: NixExpression = NixValue> {
function: NixValue,
result: std::marker::PhantomData<R>,
}
impl<R: NixExpression> PackageFunction<R> {
#[track_caller]
pub fn from_function_attrs<K: Into<String>>(
arguments: impl IntoIterator<Item = impl Into<String>>,
build: impl FnOnce(NixValue) -> (Vec<(K, NixValue)>, R),
) -> Self {
Self {
function: NixValue::function_attrs(arguments, |args| {
let (defaults, result) = build(args);
(defaults, result.as_expression())
}),
result: std::marker::PhantomData,
}
}
#[track_caller]
pub fn call(&self, arguments: impl ConfigValue) -> R {
R::from_expression(self.function.clone().call(arguments))
}
}
impl<R: NixExpression> NixRepresentation for PackageFunction<R> {
fn from_expression(function: NixValue) -> Self {
Self {
function,
result: std::marker::PhantomData,
}
}
fn as_expression(&self) -> NixValue {
self.function.clone()
}
}
impl<R: NixExpression> crate::IntoRusixValue for PackageFunction<R> {
#[track_caller]
fn into_value(self) -> crate::RusixValue {
crate::RusixValue::leaf(self)
}
}
impl<R: NixExpression> sealed::Sealed for PackageFunction<R> {}
impl<R: NixExpression> ConfigValue for PackageFunction<R> {}
impl<R: NixExpression> IntoNode for PackageFunction<R> {
fn into_node(self, _: Origin) -> Node {
self.function.0
}
}
impl<R: NixExpression> From<PackageFunction<R>> for NixValue {
fn from(value: PackageFunction<R>) -> Self {
value.function
}
}
handle!(
OverlayRef,
"A reference to a Nix function that extends or replaces packages in nixpkgs.
Such a function is called an *overlay*. It receives the final package set and
the preceding package set, then returns named additions or replacements. Pass
it to [`Nixpkgs::with_overlay`]; Nix applies it later. Rust does not inspect
package internals or verify the overlay’s function arguments. Convert it to
[`Overlay`] when composing it with authored overlays as a value."
);
impl sealed::Sealed for PackageRef {}
impl ConfigValue for PackageRef {}
impl IntoNode for PackageRef {
fn into_node(self, _: Origin) -> Node {
self.0.node()
}
}
#[macro_export]
macro_rules! nix_text {
($template:literal $(, $name:ident = $value:expr)* $(,)?) => {
$crate::__symbolic_text!($crate; $template $(, $name = $value)*)
};
($($part:expr),* $(,)?) => {
$crate::Expr::<String>::concat([$($part.into()),*])
};
}
#[macro_export]
macro_rules! nix_record {
(@key ($key:expr)) => { $key };
(@key $key:expr) => { $key };
($($key:tt : $value:expr),* $(,)?) => {{
let fields: ::std::vec::Vec<(::std::string::String, $crate::interop::raw::NixValue)> =
::std::vec![$((::std::convert::Into::into($crate::nix_record!(@key $key)), $crate::interop::raw::NixValue::from($value))),*];
$crate::interop::raw::NixValue::record(fields)
}};
}
#[derive(Clone, Debug, Default)]
pub struct Nixpkgs {
module_scope: bool,
overlays: Vec<Node>,
}
impl Nixpkgs {
pub fn new() -> Self {
Self::default()
}
#[track_caller]
pub fn source_path(&self, path: &str) -> NixPath {
NixPath::from_expression(NixValue(
Reference {
source: Source::PinnedPath { path: path.into() },
path: None,
origin: Origin::caller(format!("nixpkgs source path {path}")),
}
.node(),
))
}
pub fn from_module() -> Self {
Self {
module_scope: true,
overlays: vec![],
}
}
fn package_source(&self) -> Source {
if self.module_scope {
Source::NixosPackages {
overlays: self.overlays.clone(),
}
} else {
Source::Packages {
overlays: self.overlays.clone(),
}
}
}
pub fn with_overlay(mut self, overlay: impl Into<Overlay>) -> Self {
self.overlays.push(overlay.into().as_expression().0);
self
}
#[track_caller]
pub fn view<V: NixExpression>(&self) -> V {
V::from_expression(NixValue(
Reference {
source: self.package_source(),
path: None,
origin: Origin::caller("nixpkgs package set view"),
}
.node(),
))
}
#[track_caller]
pub fn get(&self, path: &str) -> PackageRef {
self.path(AttrPath::dotted(path).0)
}
#[track_caller]
pub fn path(&self, parts: impl IntoIterator<Item = impl Into<String>>) -> PackageRef {
let path = AttrPath::segments(parts);
let origin = Origin::caller(format!("nixpkgs package lookup {}", path.0.join(".")));
PackageRef(Reference {
source: self.package_source(),
path: Some(path),
origin,
})
}
#[track_caller]
pub fn module(&self, file: &str) -> ModuleRef {
ModuleRef(Reference {
source: Source::ModuleFile { path: file.into() },
path: None,
origin: Origin::caller(format!("NixOS module lookup {file}")),
})
}
#[track_caller]
pub fn function(&self, path: &str) -> NixFunction {
NixFunction(Reference {
source: Source::Library,
path: Some(AttrPath::dotted(path)),
origin: Origin::caller(format!("nixpkgs lib function lookup {path}")),
})
}
#[track_caller]
pub fn library(&self) -> NixLibrary {
NixLibrary::from_value(NixValue(
Reference {
source: Source::Library,
path: None,
origin: Origin::caller("nixpkgs library lookup"),
}
.node(),
))
}
#[track_caller]
pub fn call_package<R: NixExpression>(
&self,
function: &PackageFunction<R>,
overrides: impl Into<NixValue>,
) -> R {
R::from_expression(
self.pkgs_function("callPackage")
.call(function.clone())
.call(overrides.into()),
)
}
#[track_caller]
pub fn try_call_package<R: NixExpression>(
&self,
function: &PackageFunction<R>,
overrides: impl crate::IntoRusixValue,
) -> Result<R, ValidationError> {
Ok(self.call_package(function, overrides.try_into_nix_value()?))
}
#[track_caller]
pub fn pkgs_function(&self, path: &str) -> NixFunction {
NixFunction(Reference {
source: self.package_source(),
path: Some(AttrPath::dotted(path)),
origin: Origin::caller(format!("nixpkgs function lookup {path}")),
})
}
}
#[derive(Clone, Debug)]
pub struct InputRef {
source: Source,
}
impl InputRef {
pub fn local(name: impl Into<String>, file: impl Into<PathBuf>) -> Self {
Self {
source: Source::Input {
name: name.into(),
file: file.into(),
},
}
}
#[track_caller]
fn lookup(&self, path: &str, category: &str) -> Reference {
Reference {
source: self.source.clone(),
path: Some(AttrPath::dotted(path)),
origin: Origin::caller(format!("external {category} lookup {path}")),
}
}
#[track_caller]
pub fn package(&self, path: &str) -> PackageRef {
PackageRef(self.lookup(path, "package"))
}
#[track_caller]
pub fn module(&self, path: &str) -> ModuleRef {
ModuleRef(self.lookup(path, "module"))
}
#[track_caller]
pub fn function(&self, path: &str) -> NixFunction {
NixFunction(self.lookup(path, "function"))
}
#[track_caller]
pub fn overlay(&self, path: &str) -> OverlayRef {
OverlayRef(self.lookup(path, "overlay"))
}
}