How to debug nix code?


I begin to better understand the nix language and functional programming. And so I try to write more elaborated code.
But how to debug when it doesn’t build ?

For example, if I have this kind of code

   myFunc = var: ( # some elaborated code I'm proud of );
   mySet = builtins.listToAttr ( myFunc [ "a" "b" "c" ]);
   some.configuration = mySet;

and if my build fails because there’s something wrong with mySet, is there a way to display the value of mySet (some kind of var dump ?).


you may be looking for builtins.trace, you can use it like this:

let var = builtins.trace "foo" "bar"; in var

This prints trace: foo on your console and the result of this expression is the string "bar".

There are a bunch of useful functions around builtins.trace, see Debugging functions | nixpkgs

There’s also a relatively new flag called --debugger that launches an interactive debugger at the point where an evaluation failed (or at a breakpoint that can be set via builtins.break IIRC).

Btw if your code above is the problem, the function you’re most likely looking for is builtins.listToAttrs (notice the plural attrs ;-))

1 Like

Thanks, this will help me.
I was wondering how to use builtins.trace

listAttr without s is just a typo :slight_smile:

Have a look at the --debugger flag. It drops you into a REPL on eval error and you can introspect the values there.