Check for throw while evaluating throw message

This is a small tweak to the logic added in cl/1511 to detect explicit
throws when printing stack traces. Now when deciding whether to print
"caused by explicit throw", it checks not only that the error is a
ThrowError and that we are in a throw, but also that the ThrowError was
thrown by *this* throw, and not by another while in the process of
evaluating this throw's operand.

It turns this:

```
let
  set = {
    inner = throw "nested throw";
  };
in
throw set.inner

error:
       … caused by explicit throw
         at /pwd/in.nix:6:1:
            5| in
            6| throw set.inner
             | ^
            7|

       … while evaluating the attribute 'inner'
         at /pwd/in.nix:3:5:
            2|   set = {
            3|     inner = throw "nested throw";
             |     ^
            4|   };

       … caused by explicit throw
         at /pwd/in.nix:3:13:
            2|   set = {
            3|     inner = throw "nested throw";
             |             ^
            4|   };

       error: nested throw
```

into this:

```
error:
       … while calling the 'throw' builtin
         at /pwd/in.nix:6:1:
            5| in
            6| throw set.inner
             | ^
            7|

       … while evaluating the attribute 'inner'
         at /pwd/in.nix:3:5:
            2|   set = {
            3|     inner = throw "nested throw";
             |     ^
            4|   };

       … caused by explicit throw
         at /pwd/in.nix:3:13:
            2|   set = {
            3|     inner = throw "nested throw";
             |             ^
            4|   };

       error: nested throw
```

Notice the difference in the top context frame. Before it incorrectly
attributed the throw error to the both throws instead of just the one
that actually threw.

Change-Id: If3b0b8311f1ae2ff1471e260fe59d9166a6a6964
This commit is contained in:
skye
2026-04-11 12:46:24 -04:00
parent 9fea1b816f
commit e79278b4fc
3 changed files with 30 additions and 1 deletions
+1 -1
View File
@@ -1206,7 +1206,7 @@ Value EvalState::callFunction(Value & fun, std::span<Value> args, const PosIdx p
} catch (ThrownError & e) {
// Distinguish between an error that simply happened while "throw"
// was being evaluated and an explicit thrown error.
if (fn->name == "throw") {
if (fn->name == "throw" && !e.hasTrace()) {
e.addTrace(ctx.positions[pos], "caused by explicit %s", "throw");
} else {
e.addTrace(ctx.positions[pos], "while calling the '%s' builtin", fn->name);
@@ -0,0 +1,23 @@
error:
… while calling the 'throw' builtin
at /pwd/in.nix:6:1:
5| in
6| throw set.inner
| ^
7|
… while evaluating the attribute 'inner'
at /pwd/in.nix:3:5:
2| set = {
3| inner = throw "nested throw";
| ^
4| };
… caused by explicit throw
at /pwd/in.nix:3:13:
2| set = {
3| inner = throw "nested throw";
| ^
4| };
error: nested throw
@@ -0,0 +1,6 @@
let
set = {
inner = throw "nested throw";
};
in
throw set.inner