Debug a Nix expression with debug/trace statements?

Is it possible to print debug/trace statements from a Nix expression? This could be useful when trying to fix a broken derivation.

For example, I was trying to write a shell.nix that overrides an R package, and part of my file contained:

rPackageOverrides = old: {
  jqr = old.jqr.overrideDerivation (attrs: {
    preConfigure = "patchShebangs configure";
  });
};
pkgs = import <nixpkgs> { config = { inherit rPackageOverrides; }; };

Running nix-shell would complain that old had no jqr attribute: error: attribute 'jqr' missing.

It would be helpful if I could inspect some of old’s attributes. Is there a way to do that?

4 Likes

Use builtins.trace (string to output) (expr to return).
You probably also don’t want to inherit rPackageOverrides, but use packageOverrides instead.

nix-build --no-out-link - <<'EOF'
let
  packageOverrides = old: {
    jqr = builtins.trace ''jq: ${old.jq}, jqr: ${old.jqr or "unavailable"}'' old.hello;
  };
  pkgs = import <nixpkgs> { config = { inherit packageOverrides; }; };
in
  pkgs.jqr
EOF

What are you looking for in the old attributes?

4 Likes

builtins.trace looks quite helpful, thanks earvstedt! Is there something like a builtins.breakpoint that drops you into nix repl when it evaluates?

Thanks, builtins.trace is exactly what I was looking for.

I just wanted to poke around to see if old was the top-level pkgs set, or something else.

I’m using rPackageOverrides because I’m trying to modify the jqr derivation produced by r-modules by leveraging the overrides argument that r-modules/default.nix accepts. In top-level/all-packages.nix, rPackages is set like:

rPackages = callPackage ../development/r-modules {
  overrides = (config.rPackageOverrides or (p: {})) pkgs;
};

I can’t figure out how to actually accomplish this (referencing old.rPackages.jqr leads to infinite recursion), but builtins.trace is an invaluable lesson. Thanks!

No, that’s not yet possible.

Related helpers can be found in https://github.com/NixOS/nixpkgs/blob/master/lib/debug.nix

10 Likes