Contracts in Nix NEW: Now contracts are compatible with yants. The Nix language lacks a good type system. There are already several configuration languages that provide static and even gradual typing (see, e.g., Cue, Dhall, or Nickel), but none offer the ability to easily annotate legacy Nix code with types. “Contracts”, which you can now define thanks to the utilities offered in this library, come to the rescue! And because an example is worth a thousand words: { sources ? import nix/sources.nix }: with import sources.contracts { enable = true; }; # Describe fields of package.json we will later need, so if the error comes # from a malformed file, we will fail early: let package = contract { message = _: "`package.json' malformed..."; } { bundleDependencies = enum [ Bool (listOf Str) ]; dependencies = setOf Str; } (builtins.fromJSON (builtins.readFile ./package.json)); # We trust the data so we can write simpler logic, even with weird specifications: # https://docs.npmjs.com/cli/v8/configuring-npm/package-json#bundledependencies deps = with package; if Bool bundleDependencies then if bundleDependencies then dependencies else {} else let filterAttrsName = with builtins; set: xs: removeAttrs set (partition (x: elem x xs) (attrNames set)).wrong; in filterAttrsName dependencies bundleDependencies; # I leave the writing of `bundler` (or any working derivation) to the reader! # Notice that `nixpkgs` wasn't required until now: pkgs = import sources.nixpkgs {}; in derivation { name = "this-is-just-a-dumb-example"; builder = "${pkgs.bash}/bin/bash"; args = [ ./bundler (builtins.toFile "deps.json" (builtins.toJSON deps)) ]; system = builtins.currentSystem; } What’s behind such dark magic? Basic ideas (and a few lines of code): The expressiveness of the Nix language is greater than what we expect of most type systems, and good news: Nix expression computation is expected to terminate (it’s not perfect, indeed, but did you know that C++ template system resolution can loop infin...
First seen: 2026-02-02 05:32
Last seen: 2026-02-02 07:45