move throw to preverve Error type; turn off debugger for tryEval

This commit is contained in:
Ben Burdette 2022-04-08 12:34:27 -06:00
parent 1a93ac8133
commit b8b8ec7101
8 changed files with 361 additions and 140 deletions

View file

@ -50,7 +50,7 @@ struct NixRepl
ref<EvalState> state; ref<EvalState> state;
Bindings * autoArgs; Bindings * autoArgs;
const Error *debugError; const Error *debugError;
int debugTraceIndex; int debugTraceIndex;
Strings loadedFiles; Strings loadedFiles;

View file

@ -528,14 +528,22 @@ std::string AttrCursor::getString()
debug("using cached string attribute '%s'", getAttrPathStr()); debug("using cached string attribute '%s'", getAttrPathStr());
return s->first; return s->first;
} else } else
root->state.debug_throw(TypeError("'%s' is not a string", getAttrPathStr())); {
auto e = TypeError("'%s' is not a string", getAttrPathStr());
root->state.debugLastTrace(e);
throw e;
}
} }
} }
auto & v = forceValue(); auto & v = forceValue();
if (v.type() != nString && v.type() != nPath) if (v.type() != nString && v.type() != nPath)
root->state.debug_throw(TypeError("'%s' is not a string but %s", getAttrPathStr(), showType(v.type()))); {
auto e = TypeError("'%s' is not a string but %s", getAttrPathStr(), showType(v.type()));
root->state.debugLastTrace(e);
throw e;
}
return v.type() == nString ? v.string.s : v.path; return v.type() == nString ? v.string.s : v.path;
} }
@ -559,7 +567,11 @@ string_t AttrCursor::getStringWithContext()
return *s; return *s;
} }
} else } else
root->state.debug_throw(TypeError("'%s' is not a string", getAttrPathStr())); {
auto e = TypeError("'%s' is not a string", getAttrPathStr());
root->state.debugLastTrace(e);
throw e;
}
} }
} }
@ -571,7 +583,9 @@ string_t AttrCursor::getStringWithContext()
return {v.path, {}}; return {v.path, {}};
else else
{ {
root->state.debug_throw(TypeError("'%s' is not a string but %s", getAttrPathStr(), showType(v.type()))); auto e = TypeError("'%s' is not a string but %s", getAttrPathStr(), showType(v.type()));
root->state.debugLastTrace(e);
throw e;
return {v.path, {}}; // should never execute return {v.path, {}}; // should never execute
} }
} }
@ -586,14 +600,22 @@ bool AttrCursor::getBool()
debug("using cached Boolean attribute '%s'", getAttrPathStr()); debug("using cached Boolean attribute '%s'", getAttrPathStr());
return *b; return *b;
} else } else
root->state.debug_throw(TypeError("'%s' is not a Boolean", getAttrPathStr())); {
auto e = TypeError("'%s' is not a Boolean", getAttrPathStr());
root->state.debugLastTrace(e);
throw e;
}
} }
} }
auto & v = forceValue(); auto & v = forceValue();
if (v.type() != nBool) if (v.type() != nBool)
root->state.debug_throw(TypeError("'%s' is not a Boolean", getAttrPathStr())); {
auto e = TypeError("'%s' is not a Boolean", getAttrPathStr());
root->state.debugLastTrace(e);
throw e;
}
return v.boolean; return v.boolean;
} }
@ -608,14 +630,22 @@ std::vector<Symbol> AttrCursor::getAttrs()
debug("using cached attrset attribute '%s'", getAttrPathStr()); debug("using cached attrset attribute '%s'", getAttrPathStr());
return *attrs; return *attrs;
} else } else
root->state.debug_throw(TypeError("'%s' is not an attribute set", getAttrPathStr())); {
auto e = TypeError("'%s' is not an attribute set", getAttrPathStr());
root->state.debugLastTrace(e);
throw e;
}
} }
} }
auto & v = forceValue(); auto & v = forceValue();
if (v.type() != nAttrs) if (v.type() != nAttrs)
root->state.debug_throw(TypeError("'%s' is not an attribute set", getAttrPathStr())); {
auto e = TypeError("'%s' is not an attribute set", getAttrPathStr());
root->state.debugLastTrace(e);
throw e;
}
std::vector<Symbol> attrs; std::vector<Symbol> attrs;
for (auto & attr : *getValue().attrs) for (auto & attr : *getValue().attrs)

View file

@ -833,15 +833,13 @@ LocalNoInlineNoReturn(void throwEvalError(const char * s, const std::string & s2
throw error; throw error;
} }
void EvalState::debug_throw(Error e) { void EvalState::debugLastTrace(Error & e) {
// call this in the situation where Expr and Env are inaccessible. The debugger will start in the last context // call this in the situation where Expr and Env are inaccessible. The debugger will start in the last context
// that's in the DebugTrace stack. // that's in the DebugTrace stack.
if (debuggerHook && !debugTraces.empty()) { if (debuggerHook && !debugTraces.empty()) {
DebugTrace &last = debugTraces.front(); DebugTrace &last = debugTraces.front();
debuggerHook(&e, last.env, last.expr); debuggerHook(&e, last.env, last.expr);
} }
throw e;
} }
LocalNoInlineNoReturn(void throwEvalError(const Pos & pos, const Suggestions & suggestions, const char * s, const std::string & s2, Env & env, Expr &expr)) LocalNoInlineNoReturn(void throwEvalError(const Pos & pos, const Suggestions & suggestions, const char * s, const std::string & s2, Env & env, Expr &expr))
@ -865,10 +863,7 @@ LocalNoInlineNoReturn(void throwEvalError(const Pos & pos, const char * s, const
.errPos = pos .errPos = pos
}); });
if (debuggerHook && !evalState.debugTraces.empty()) { evalState.debugLastTrace(error);
DebugTrace &last = evalState.debugTraces.front();
debuggerHook(&error, last.env, last.expr);
}
throw error; throw error;
} }
@ -906,10 +901,7 @@ LocalNoInlineNoReturn(void throwEvalError(const Pos & pos, const char * s, const
.errPos = pos .errPos = pos
}); });
if (debuggerHook && !evalState.debugTraces.empty()) { evalState.debugLastTrace(error);
DebugTrace &last = evalState.debugTraces.front();
debuggerHook(&error, last.env, last.expr);
}
throw error; throw error;
} }
@ -921,10 +913,7 @@ LocalNoInlineNoReturn(void throwEvalError(const char * s, const std::string & s2
.errPos = noPos .errPos = noPos
}); });
if (debuggerHook && !evalState.debugTraces.empty()) { evalState.debugLastTrace(error);
DebugTrace &last = evalState.debugTraces.front();
debuggerHook(&error, last.env, last.expr);
}
throw error; throw error;
} }
@ -950,10 +939,7 @@ LocalNoInlineNoReturn(void throwTypeError(const Pos & pos, const char * s, EvalS
.errPos = pos .errPos = pos
}); });
if (debuggerHook && !evalState.debugTraces.empty()) { evalState.debugLastTrace(error);
DebugTrace &last = evalState.debugTraces.front();
debuggerHook(&error, last.env, last.expr);
}
throw error; throw error;
} }
@ -972,8 +958,6 @@ LocalNoInlineNoReturn(void throwTypeError(const Pos & pos, const char * s, const
throw error; throw error;
} }
// LocalNoInlineNoReturn(void throwTypeError(const char * s, const Value & v));
LocalNoInlineNoReturn(void throwTypeError(const Pos & pos, const char * s, const ExprLambda & fun, const Symbol & s2, Env & env, Expr &expr)) LocalNoInlineNoReturn(void throwTypeError(const Pos & pos, const char * s, const ExprLambda & fun, const Symbol & s2, Env & env, Expr &expr))
{ {
auto error = TypeError({ auto error = TypeError({

View file

@ -119,7 +119,7 @@ public:
bool debugStop; bool debugStop;
bool debugQuit; bool debugQuit;
std::list<DebugTrace> debugTraces; std::list<DebugTrace> debugTraces;
void debug_throw(Error e); void debugLastTrace(Error & e);
private: private:
SrcToStore srcToStore; SrcToStore srcToStore;

View file

@ -783,14 +783,15 @@ Path EvalState::findFile(SearchPath & searchPath, const std::string_view path, c
if (hasPrefix(path, "nix/")) if (hasPrefix(path, "nix/"))
return concatStrings(corepkgsPrefix, path.substr(4)); return concatStrings(corepkgsPrefix, path.substr(4));
debug_throw(ThrownError({ auto e = ThrownError({
.msg = hintfmt(evalSettings.pureEval .msg = hintfmt(evalSettings.pureEval
? "cannot look up '<%s>' in pure evaluation mode (use '--impure' to override)" ? "cannot look up '<%s>' in pure evaluation mode (use '--impure' to override)"
: "file '%s' was not found in the Nix search path (add it using $NIX_PATH or -I)", : "file '%s' was not found in the Nix search path (add it using $NIX_PATH or -I)",
path), path),
.errPos = pos .errPos = pos
})); });
return Path(); // should never execute due to debug_throw above. debugLastTrace(e);
throw e;
} }

View file

@ -46,7 +46,11 @@ StringMap EvalState::realiseContext(const PathSet & context)
auto [ctx, outputName] = decodeContext(*store, i); auto [ctx, outputName] = decodeContext(*store, i);
auto ctxS = store->printStorePath(ctx); auto ctxS = store->printStorePath(ctx);
if (!store->isValidPath(ctx)) if (!store->isValidPath(ctx))
debug_throw(InvalidPathError(store->printStorePath(ctx))); {
auto e = InvalidPathError(store->printStorePath(ctx));
debugLastTrace(e);
throw e;
}
if (!outputName.empty() && ctx.isDerivation()) { if (!outputName.empty() && ctx.isDerivation()) {
drvs.push_back({ctx, {outputName}}); drvs.push_back({ctx, {outputName}});
} else { } else {
@ -57,9 +61,13 @@ StringMap EvalState::realiseContext(const PathSet & context)
if (drvs.empty()) return {}; if (drvs.empty()) return {};
if (!evalSettings.enableImportFromDerivation) if (!evalSettings.enableImportFromDerivation)
debug_throw(Error( {
auto e = Error(
"cannot build '%1%' during evaluation because the option 'allow-import-from-derivation' is disabled", "cannot build '%1%' during evaluation because the option 'allow-import-from-derivation' is disabled",
store->printStorePath(drvs.begin()->drvPath))); store->printStorePath(drvs.begin()->drvPath));
debugLastTrace(e);
throw e;
}
/* Build/substitute the context. */ /* Build/substitute the context. */
std::vector<DerivedPath> buildReqs; std::vector<DerivedPath> buildReqs;
@ -71,8 +79,12 @@ StringMap EvalState::realiseContext(const PathSet & context)
auto outputPaths = store->queryDerivationOutputMap(drvPath); auto outputPaths = store->queryDerivationOutputMap(drvPath);
for (auto & outputName : outputs) { for (auto & outputName : outputs) {
if (outputPaths.count(outputName) == 0) if (outputPaths.count(outputName) == 0)
debug_throw(Error("derivation '%s' does not have an output named '%s'", {
store->printStorePath(drvPath), outputName)); auto e = Error("derivation '%s' does not have an output named '%s'",
store->printStorePath(drvPath), outputName);
debugLastTrace(e);
throw e;
}
res.insert_or_assign( res.insert_or_assign(
downstreamPlaceholder(*store, drvPath, outputName), downstreamPlaceholder(*store, drvPath, outputName),
store->printStorePath(outputPaths.at(outputName)) store->printStorePath(outputPaths.at(outputName))
@ -318,17 +330,29 @@ void prim_importNative(EvalState & state, const Pos & pos, Value * * args, Value
void *handle = dlopen(path.c_str(), RTLD_LAZY | RTLD_LOCAL); void *handle = dlopen(path.c_str(), RTLD_LAZY | RTLD_LOCAL);
if (!handle) if (!handle)
state.debug_throw(EvalError("could not open '%1%': %2%", path, dlerror())); {
auto e = EvalError("could not open '%1%': %2%", path, dlerror());
state.debugLastTrace(e);
throw e;
}
dlerror(); dlerror();
ValueInitializer func = (ValueInitializer) dlsym(handle, sym.c_str()); ValueInitializer func = (ValueInitializer) dlsym(handle, sym.c_str());
if(!func) { if(!func) {
char *message = dlerror(); char *message = dlerror();
if (message) if (message)
state.debug_throw(EvalError("could not load symbol '%1%' from '%2%': %3%", sym, path, message)); {
auto e = EvalError("could not load symbol '%1%' from '%2%': %3%", sym, path, message);
state.debugLastTrace(e);
throw e;
}
else else
state.debug_throw(EvalError("symbol '%1%' from '%2%' resolved to NULL when a function pointer was expected", {
sym, path)); auto e = EvalError("symbol '%1%' from '%2%' resolved to NULL when a function pointer was expected",
sym, path);
state.debugLastTrace(e);
throw e;
}
} }
(func)(state, v); (func)(state, v);
@ -344,10 +368,12 @@ void prim_exec(EvalState & state, const Pos & pos, Value * * args, Value & v)
auto elems = args[0]->listElems(); auto elems = args[0]->listElems();
auto count = args[0]->listSize(); auto count = args[0]->listSize();
if (count == 0) { if (count == 0) {
state.debug_throw(EvalError({ auto e = EvalError({
.msg = hintfmt("at least one argument to 'exec' required"), .msg = hintfmt("at least one argument to 'exec' required"),
.errPos = pos .errPos = pos
})); });
state.debugLastTrace(e);
throw e;
} }
PathSet context; PathSet context;
auto program = state.coerceToString(pos, *elems[0], context, false, false).toOwned(); auto program = state.coerceToString(pos, *elems[0], context, false, false).toOwned();
@ -358,11 +384,13 @@ void prim_exec(EvalState & state, const Pos & pos, Value * * args, Value & v)
try { try {
auto _ = state.realiseContext(context); // FIXME: Handle CA derivations auto _ = state.realiseContext(context); // FIXME: Handle CA derivations
} catch (InvalidPathError & e) { } catch (InvalidPathError & e) {
state.debug_throw(EvalError({ auto ee = EvalError({
.msg = hintfmt("cannot execute '%1%', since path '%2%' is not valid", .msg = hintfmt("cannot execute '%1%', since path '%2%' is not valid",
program, e.path), program, e.path),
.errPos = pos .errPos = pos
})); });
state.debugLastTrace(ee);
throw ee;
} }
auto output = runProgram(program, true, commandArgs); auto output = runProgram(program, true, commandArgs);
@ -545,7 +573,11 @@ struct CompareValues
if (v1->type() == nInt && v2->type() == nFloat) if (v1->type() == nInt && v2->type() == nFloat)
return v1->integer < v2->fpoint; return v1->integer < v2->fpoint;
if (v1->type() != v2->type()) if (v1->type() != v2->type())
state.debug_throw(EvalError("cannot compare %1% with %2%", showType(*v1), showType(*v2))); {
auto e = EvalError("cannot compare %1% with %2%", showType(*v1), showType(*v2));
state.debugLastTrace(e);
throw e;
}
switch (v1->type()) { switch (v1->type()) {
case nInt: case nInt:
return v1->integer < v2->integer; return v1->integer < v2->integer;
@ -567,8 +599,11 @@ struct CompareValues
} }
} }
default: default:
state.debug_throw(EvalError("cannot compare %1% with %2%", showType(*v1), showType(*v2))); {
return false; auto e = EvalError("cannot compare %1% with %2%", showType(*v1), showType(*v2));
state.debugLastTrace(e);
throw e;
}
} }
} }
}; };
@ -598,10 +633,12 @@ static Bindings::iterator getAttr(
Pos aPos = *attrSet->pos; Pos aPos = *attrSet->pos;
if (aPos == noPos) { if (aPos == noPos) {
state.debug_throw(TypeError({ auto e = TypeError({
.msg = errorMsg, .msg = errorMsg,
.errPos = pos, .errPos = pos,
})); });
state.debugLastTrace(e);
throw e;
} else { } else {
auto e = TypeError({ auto e = TypeError({
.msg = errorMsg, .msg = errorMsg,
@ -611,7 +648,8 @@ static Bindings::iterator getAttr(
// Adding another trace for the function name to make it clear // Adding another trace for the function name to make it clear
// which call received wrong arguments. // which call received wrong arguments.
e.addTrace(pos, hintfmt("while invoking '%s'", funcName)); e.addTrace(pos, hintfmt("while invoking '%s'", funcName));
state.debug_throw(e); state.debugLastTrace(e);
throw e;
} }
} }
@ -665,10 +703,14 @@ static void prim_genericClosure(EvalState & state, const Pos & pos, Value * * ar
Bindings::iterator key = Bindings::iterator key =
e->attrs->find(state.sKey); e->attrs->find(state.sKey);
if (key == e->attrs->end()) if (key == e->attrs->end())
state.debug_throw(EvalError({ {
auto e = EvalError({
.msg = hintfmt("attribute 'key' required"), .msg = hintfmt("attribute 'key' required"),
.errPos = pos .errPos = pos
})); });
state.debugLastTrace(e);
throw e;
}
state.forceValue(*key->value, pos); state.forceValue(*key->value, pos);
if (!doneKeys.insert(key->value).second) continue; if (!doneKeys.insert(key->value).second) continue;
@ -768,7 +810,11 @@ static RegisterPrimOp primop_abort({
{ {
PathSet context; PathSet context;
auto s = state.coerceToString(pos, *args[0], context).toOwned(); auto s = state.coerceToString(pos, *args[0], context).toOwned();
state.debug_throw(Abort("evaluation aborted with the following error message: '%1%'", s)); {
auto e = Abort("evaluation aborted with the following error message: '%1%'", s);
state.debugLastTrace(e);
throw e;
}
} }
}); });
@ -786,7 +832,9 @@ static RegisterPrimOp primop_throw({
{ {
PathSet context; PathSet context;
auto s = state.coerceToString(pos, *args[0], context).toOwned(); auto s = state.coerceToString(pos, *args[0], context).toOwned();
state.debug_throw(ThrownError(s)); auto e = ThrownError(s);
state.debugLastTrace(e);
throw e;
} }
}); });
@ -851,6 +899,8 @@ static RegisterPrimOp primop_floor({
static void prim_tryEval(EvalState & state, const Pos & pos, Value * * args, Value & v) static void prim_tryEval(EvalState & state, const Pos & pos, Value * * args, Value & v)
{ {
auto attrs = state.buildBindings(2); auto attrs = state.buildBindings(2);
auto saveDebuggerHook = debuggerHook;
debuggerHook = 0;
try { try {
state.forceValue(*args[0], pos); state.forceValue(*args[0], pos);
attrs.insert(state.sValue, args[0]); attrs.insert(state.sValue, args[0]);
@ -859,6 +909,7 @@ static void prim_tryEval(EvalState & state, const Pos & pos, Value * * args, Val
attrs.alloc(state.sValue).mkBool(false); attrs.alloc(state.sValue).mkBool(false);
attrs.alloc("success").mkBool(false); attrs.alloc("success").mkBool(false);
} }
debuggerHook = saveDebuggerHook;
v.mkAttrs(attrs); v.mkAttrs(attrs);
} }
@ -1041,37 +1092,53 @@ static void prim_derivationStrict(EvalState & state, const Pos & pos, Value * *
if (s == "recursive") ingestionMethod = FileIngestionMethod::Recursive; if (s == "recursive") ingestionMethod = FileIngestionMethod::Recursive;
else if (s == "flat") ingestionMethod = FileIngestionMethod::Flat; else if (s == "flat") ingestionMethod = FileIngestionMethod::Flat;
else else
state.debug_throw(EvalError({ {
auto e = EvalError({
.msg = hintfmt("invalid value '%s' for 'outputHashMode' attribute", s), .msg = hintfmt("invalid value '%s' for 'outputHashMode' attribute", s),
.errPos = posDrvName .errPos = posDrvName
})); });
state.debugLastTrace(e);
throw e;
}
}; };
auto handleOutputs = [&](const Strings & ss) { auto handleOutputs = [&](const Strings & ss) {
outputs.clear(); outputs.clear();
for (auto & j : ss) { for (auto & j : ss) {
if (outputs.find(j) != outputs.end()) if (outputs.find(j) != outputs.end())
state.debug_throw(EvalError({ {
auto e = EvalError({
.msg = hintfmt("duplicate derivation output '%1%'", j), .msg = hintfmt("duplicate derivation output '%1%'", j),
.errPos = posDrvName .errPos = posDrvName
})); });
state.debugLastTrace(e);
throw e;
}
/* !!! Check whether j is a valid attribute /* !!! Check whether j is a valid attribute
name. */ name. */
/* Derivations cannot be named drv, because /* Derivations cannot be named drv, because
then we'd have an attribute drvPath in then we'd have an attribute drvPath in
the resulting set. */ the resulting set. */
if (j == "drv") if (j == "drv")
state.debug_throw(EvalError({ {
auto e = EvalError({
.msg = hintfmt("invalid derivation output name 'drv'" ), .msg = hintfmt("invalid derivation output name 'drv'" ),
.errPos = posDrvName .errPos = posDrvName
})); });
state.debugLastTrace(e);
throw e;
}
outputs.insert(j); outputs.insert(j);
} }
if (outputs.empty()) if (outputs.empty())
state.debug_throw(EvalError({ {
auto e = EvalError({
.msg = hintfmt("derivation cannot have an empty set of outputs"), .msg = hintfmt("derivation cannot have an empty set of outputs"),
.errPos = posDrvName .errPos = posDrvName
})); });
state.debugLastTrace(e);
throw e;
}
}; };
try { try {
@ -1196,23 +1263,35 @@ static void prim_derivationStrict(EvalState & state, const Pos & pos, Value * *
/* Do we have all required attributes? */ /* Do we have all required attributes? */
if (drv.builder == "") if (drv.builder == "")
state.debug_throw(EvalError({ {
auto e = EvalError({
.msg = hintfmt("required attribute 'builder' missing"), .msg = hintfmt("required attribute 'builder' missing"),
.errPos = posDrvName .errPos = posDrvName
})); });
state.debugLastTrace(e);
throw e;
}
if (drv.platform == "") if (drv.platform == "")
state.debug_throw(EvalError({ {
auto e = EvalError({
.msg = hintfmt("required attribute 'system' missing"), .msg = hintfmt("required attribute 'system' missing"),
.errPos = posDrvName .errPos = posDrvName
})); });
state.debugLastTrace(e);
throw e;
}
/* Check whether the derivation name is valid. */ /* Check whether the derivation name is valid. */
if (isDerivation(drvName)) if (isDerivation(drvName))
state.debug_throw(EvalError({ {
auto e = EvalError({
.msg = hintfmt("derivation names are not allowed to end in '%s'", drvExtension), .msg = hintfmt("derivation names are not allowed to end in '%s'", drvExtension),
.errPos = posDrvName .errPos = posDrvName
})); });
state.debugLastTrace(e);
throw e;
}
if (outputHash) { if (outputHash) {
/* Handle fixed-output derivations. /* Handle fixed-output derivations.
@ -1220,10 +1299,14 @@ static void prim_derivationStrict(EvalState & state, const Pos & pos, Value * *
Ignore `__contentAddressed` because fixed output derivations are Ignore `__contentAddressed` because fixed output derivations are
already content addressed. */ already content addressed. */
if (outputs.size() != 1 || *(outputs.begin()) != "out") if (outputs.size() != 1 || *(outputs.begin()) != "out")
state.debug_throw(Error({ {
auto e = Error({
.msg = hintfmt("multiple outputs are not supported in fixed-output derivations"), .msg = hintfmt("multiple outputs are not supported in fixed-output derivations"),
.errPos = posDrvName .errPos = posDrvName
})); });
state.debugLastTrace(e);
throw e;
}
auto h = newHashAllowEmpty(*outputHash, parseHashTypeOpt(outputHashAlgo)); auto h = newHashAllowEmpty(*outputHash, parseHashTypeOpt(outputHashAlgo));
@ -1386,10 +1469,14 @@ static RegisterPrimOp primop_toPath({
static void prim_storePath(EvalState & state, const Pos & pos, Value * * args, Value & v) static void prim_storePath(EvalState & state, const Pos & pos, Value * * args, Value & v)
{ {
if (evalSettings.pureEval) if (evalSettings.pureEval)
state.debug_throw(EvalError({ {
auto e = EvalError({
.msg = hintfmt("'%s' is not allowed in pure evaluation mode", "builtins.storePath"), .msg = hintfmt("'%s' is not allowed in pure evaluation mode", "builtins.storePath"),
.errPos = pos .errPos = pos
})); });
state.debugLastTrace(e);
throw e;
}
PathSet context; PathSet context;
Path path = state.checkSourcePath(state.coerceToPath(pos, *args[0], context)); Path path = state.checkSourcePath(state.coerceToPath(pos, *args[0], context));
@ -1398,10 +1485,14 @@ static void prim_storePath(EvalState & state, const Pos & pos, Value * * args, V
e.g. nix-push does the right thing. */ e.g. nix-push does the right thing. */
if (!state.store->isStorePath(path)) path = canonPath(path, true); if (!state.store->isStorePath(path)) path = canonPath(path, true);
if (!state.store->isInStore(path)) if (!state.store->isInStore(path))
state.debug_throw(EvalError({ {
auto e = EvalError({
.msg = hintfmt("path '%1%' is not in the Nix store", path), .msg = hintfmt("path '%1%' is not in the Nix store", path),
.errPos = pos .errPos = pos
})); });
state.debugLastTrace(e);
throw e;
}
auto path2 = state.store->toStorePath(path).first; auto path2 = state.store->toStorePath(path).first;
if (!settings.readOnlyMode) if (!settings.readOnlyMode)
state.store->ensurePath(path2); state.store->ensurePath(path2);
@ -1504,7 +1595,11 @@ static void prim_readFile(EvalState & state, const Pos & pos, Value * * args, Va
auto path = realisePath(state, pos, *args[0]); auto path = realisePath(state, pos, *args[0]);
auto s = readFile(path); auto s = readFile(path);
if (s.find((char) 0) != std::string::npos) if (s.find((char) 0) != std::string::npos)
state.debug_throw(Error("the contents of the file '%1%' cannot be represented as a Nix string", path)); {
auto e = Error("the contents of the file '%1%' cannot be represented as a Nix string", path);
state.debugLastTrace(e);
throw e;
}
StorePathSet refs; StorePathSet refs;
if (state.store->isInStore(path)) { if (state.store->isInStore(path)) {
try { try {
@ -1556,10 +1651,12 @@ static void prim_findFile(EvalState & state, const Pos & pos, Value * * args, Va
auto rewrites = state.realiseContext(context); auto rewrites = state.realiseContext(context);
path = rewriteStrings(path, rewrites); path = rewriteStrings(path, rewrites);
} catch (InvalidPathError & e) { } catch (InvalidPathError & e) {
state.debug_throw(EvalError({ auto ee = EvalError({
.msg = hintfmt("cannot find '%1%', since path '%2%' is not valid", path, e.path), .msg = hintfmt("cannot find '%1%', since path '%2%' is not valid", path, e.path),
.errPos = pos .errPos = pos
})); });
state.debugLastTrace(ee);
throw ee;
} }
@ -1583,10 +1680,14 @@ static void prim_hashFile(EvalState & state, const Pos & pos, Value * * args, Va
auto type = state.forceStringNoCtx(*args[0], pos); auto type = state.forceStringNoCtx(*args[0], pos);
std::optional<HashType> ht = parseHashType(type); std::optional<HashType> ht = parseHashType(type);
if (!ht) if (!ht)
state.debug_throw(Error({ {
auto e = Error({
.msg = hintfmt("unknown hash type '%1%'", type), .msg = hintfmt("unknown hash type '%1%'", type),
.errPos = pos .errPos = pos
})); });
state.debugLastTrace(e);
throw e;
}
auto path = realisePath(state, pos, *args[1]); auto path = realisePath(state, pos, *args[1]);
@ -1823,13 +1924,17 @@ static void prim_toFile(EvalState & state, const Pos & pos, Value * * args, Valu
for (auto path : context) { for (auto path : context) {
if (path.at(0) != '/') if (path.at(0) != '/')
state.debug_throw(EvalError( { {
auto e = EvalError( {
.msg = hintfmt( .msg = hintfmt(
"in 'toFile': the file named '%1%' must not contain a reference " "in 'toFile': the file named '%1%' must not contain a reference "
"to a derivation but contains (%2%)", "to a derivation but contains (%2%)",
name, path), name, path),
.errPos = pos .errPos = pos
})); });
state.debugLastTrace(e);
throw e;
}
refs.insert(state.store->parseStorePath(path)); refs.insert(state.store->parseStorePath(path));
} }
@ -1986,7 +2091,11 @@ static void addPath(
? state.store->computeStorePathForPath(name, path, method, htSHA256, filter).first ? state.store->computeStorePathForPath(name, path, method, htSHA256, filter).first
: state.store->addToStore(name, path, method, htSHA256, filter, state.repair, refs); : state.store->addToStore(name, path, method, htSHA256, filter, state.repair, refs);
if (expectedHash && expectedStorePath != dstPath) if (expectedHash && expectedStorePath != dstPath)
state.debug_throw(Error("store path mismatch in (possibly filtered) path added from '%s'", path)); {
auto e = Error("store path mismatch in (possibly filtered) path added from '%s'", path);
state.debugLastTrace(e);
throw e;
}
state.allowAndSetStorePathString(dstPath, v); state.allowAndSetStorePathString(dstPath, v);
} else } else
state.allowAndSetStorePathString(*expectedStorePath, v); state.allowAndSetStorePathString(*expectedStorePath, v);
@ -2004,12 +2113,16 @@ static void prim_filterSource(EvalState & state, const Pos & pos, Value * * args
state.forceValue(*args[0], pos); state.forceValue(*args[0], pos);
if (args[0]->type() != nFunction) if (args[0]->type() != nFunction)
state.debug_throw(TypeError({ {
auto e = TypeError({
.msg = hintfmt( .msg = hintfmt(
"first argument in call to 'filterSource' is not a function but %1%", "first argument in call to 'filterSource' is not a function but %1%",
showType(*args[0])), showType(*args[0])),
.errPos = pos .errPos = pos
})); });
state.debugLastTrace(e);
throw e;
}
addPath(state, pos, std::string(baseNameOf(path)), path, args[0], FileIngestionMethod::Recursive, std::nullopt, v, context); addPath(state, pos, std::string(baseNameOf(path)), path, args[0], FileIngestionMethod::Recursive, std::nullopt, v, context);
} }
@ -2093,16 +2206,24 @@ static void prim_path(EvalState & state, const Pos & pos, Value * * args, Value
else if (n == "sha256") else if (n == "sha256")
expectedHash = newHashAllowEmpty(state.forceStringNoCtx(*attr.value, *attr.pos), htSHA256); expectedHash = newHashAllowEmpty(state.forceStringNoCtx(*attr.value, *attr.pos), htSHA256);
else else
state.debug_throw(EvalError({ {
auto e = EvalError({
.msg = hintfmt("unsupported argument '%1%' to 'addPath'", attr.name), .msg = hintfmt("unsupported argument '%1%' to 'addPath'", attr.name),
.errPos = *attr.pos .errPos = *attr.pos
})); });
state.debugLastTrace(e);
throw e;
}
} }
if (path.empty()) if (path.empty())
state.debug_throw(EvalError({ {
auto e = EvalError({
.msg = hintfmt("'path' required"), .msg = hintfmt("'path' required"),
.errPos = pos .errPos = pos
})); });
state.debugLastTrace(e);
throw e;
}
if (name.empty()) if (name.empty())
name = baseNameOf(path); name = baseNameOf(path);
@ -2473,10 +2594,14 @@ static void prim_functionArgs(EvalState & state, const Pos & pos, Value * * args
return; return;
} }
if (!args[0]->isLambda()) if (!args[0]->isLambda())
state.debug_throw(TypeError({ {
auto e = TypeError({
.msg = hintfmt("'functionArgs' requires a function"), .msg = hintfmt("'functionArgs' requires a function"),
.errPos = pos .errPos = pos
})); });
state.debugLastTrace(e);
throw e;
}
if (!args[0]->lambda.fun->hasFormals()) { if (!args[0]->lambda.fun->hasFormals()) {
v.mkAttrs(&state.emptyBindings); v.mkAttrs(&state.emptyBindings);
@ -2564,7 +2689,8 @@ static void prim_zipAttrsWith(EvalState & state, const Pos & pos, Value * * args
attrsSeen[attr.name].first++; attrsSeen[attr.name].first++;
} catch (TypeError & e) { } catch (TypeError & e) {
e.addTrace(pos, hintfmt("while invoking '%s'", "zipAttrsWith")); e.addTrace(pos, hintfmt("while invoking '%s'", "zipAttrsWith"));
state.debug_throw(e); state.debugLastTrace(e);
throw e;
} }
} }
@ -2651,10 +2777,14 @@ static void elemAt(EvalState & state, const Pos & pos, Value & list, int n, Valu
{ {
state.forceList(list, pos); state.forceList(list, pos);
if (n < 0 || (unsigned int) n >= list.listSize()) if (n < 0 || (unsigned int) n >= list.listSize())
state.debug_throw(Error({ {
auto e = Error({
.msg = hintfmt("list index %1% is out of boundz", n), .msg = hintfmt("list index %1% is out of boundz", n),
.errPos = pos .errPos = pos
})); });
state.debugLastTrace(e);
throw e;
}
state.forceValue(*list.listElems()[n], pos); state.forceValue(*list.listElems()[n], pos);
v = *list.listElems()[n]; v = *list.listElems()[n];
} }
@ -2699,10 +2829,14 @@ static void prim_tail(EvalState & state, const Pos & pos, Value * * args, Value
{ {
state.forceList(*args[0], pos); state.forceList(*args[0], pos);
if (args[0]->listSize() == 0) if (args[0]->listSize() == 0)
state.debug_throw(Error({ {
auto e = Error({
.msg = hintfmt("'tail' called on an empty list"), .msg = hintfmt("'tail' called on an empty list"),
.errPos = pos .errPos = pos
})); });
state.debugLastTrace(e);
throw e;
}
state.mkList(v, args[0]->listSize() - 1); state.mkList(v, args[0]->listSize() - 1);
for (unsigned int n = 0; n < v.listSize(); ++n) for (unsigned int n = 0; n < v.listSize(); ++n)
@ -2937,10 +3071,14 @@ static void prim_genList(EvalState & state, const Pos & pos, Value * * args, Val
auto len = state.forceInt(*args[1], pos); auto len = state.forceInt(*args[1], pos);
if (len < 0) if (len < 0)
state.debug_throw(EvalError({ {
auto e = EvalError({
.msg = hintfmt("cannot create list of size %1%", len), .msg = hintfmt("cannot create list of size %1%", len),
.errPos = pos .errPos = pos
})); });
state.debugLastTrace(e);
throw e;
}
state.mkList(v, len); state.mkList(v, len);
@ -3149,7 +3287,8 @@ static void prim_concatMap(EvalState & state, const Pos & pos, Value * * args, V
state.forceList(lists[n], lists[n].determinePos(args[0]->determinePos(pos))); state.forceList(lists[n], lists[n].determinePos(args[0]->determinePos(pos)));
} catch (TypeError &e) { } catch (TypeError &e) {
e.addTrace(pos, hintfmt("while invoking '%s'", "concatMap")); e.addTrace(pos, hintfmt("while invoking '%s'", "concatMap"));
state.debug_throw(e); state.debugLastTrace(e);
throw e;
} }
len += lists[n].listSize(); len += lists[n].listSize();
} }
@ -3244,10 +3383,14 @@ static void prim_div(EvalState & state, const Pos & pos, Value * * args, Value &
NixFloat f2 = state.forceFloat(*args[1], pos); NixFloat f2 = state.forceFloat(*args[1], pos);
if (f2 == 0) if (f2 == 0)
state.debug_throw(EvalError({ {
auto e = EvalError({
.msg = hintfmt("division by zero"), .msg = hintfmt("division by zero"),
.errPos = pos .errPos = pos
})); });
state.debugLastTrace(e);
throw e;
}
if (args[0]->type() == nFloat || args[1]->type() == nFloat) { if (args[0]->type() == nFloat || args[1]->type() == nFloat) {
v.mkFloat(state.forceFloat(*args[0], pos) / state.forceFloat(*args[1], pos)); v.mkFloat(state.forceFloat(*args[0], pos) / state.forceFloat(*args[1], pos));
@ -3256,10 +3399,14 @@ static void prim_div(EvalState & state, const Pos & pos, Value * * args, Value &
NixInt i2 = state.forceInt(*args[1], pos); NixInt i2 = state.forceInt(*args[1], pos);
/* Avoid division overflow as it might raise SIGFPE. */ /* Avoid division overflow as it might raise SIGFPE. */
if (i1 == std::numeric_limits<NixInt>::min() && i2 == -1) if (i1 == std::numeric_limits<NixInt>::min() && i2 == -1)
state.debug_throw(EvalError({ {
auto e = EvalError({
.msg = hintfmt("overflow in integer division"), .msg = hintfmt("overflow in integer division"),
.errPos = pos .errPos = pos
})); });
state.debugLastTrace(e);
throw e;
}
v.mkInt(i1 / i2); v.mkInt(i1 / i2);
} }
@ -3387,10 +3534,14 @@ static void prim_substring(EvalState & state, const Pos & pos, Value * * args, V
auto s = state.coerceToString(pos, *args[2], context); auto s = state.coerceToString(pos, *args[2], context);
if (start < 0) if (start < 0)
state.debug_throw(EvalError({ {
auto e = EvalError({
.msg = hintfmt("negative start position in 'substring'"), .msg = hintfmt("negative start position in 'substring'"),
.errPos = pos .errPos = pos
})); });
state.debugLastTrace(e);
throw e;
}
v.mkString((unsigned int) start >= s->size() ? "" : s->substr(start, len), context); v.mkString((unsigned int) start >= s->size() ? "" : s->substr(start, len), context);
} }
@ -3438,10 +3589,14 @@ static void prim_hashString(EvalState & state, const Pos & pos, Value * * args,
auto type = state.forceStringNoCtx(*args[0], pos); auto type = state.forceStringNoCtx(*args[0], pos);
std::optional<HashType> ht = parseHashType(type); std::optional<HashType> ht = parseHashType(type);
if (!ht) if (!ht)
state.debug_throw(Error({ {
auto e = Error({
.msg = hintfmt("unknown hash type '%1%'", type), .msg = hintfmt("unknown hash type '%1%'", type),
.errPos = pos .errPos = pos
})); });
state.debugLastTrace(e);
throw e;
}
PathSet context; // discarded PathSet context; // discarded
auto s = state.forceString(*args[1], context, pos); auto s = state.forceString(*args[1], context, pos);
@ -3511,15 +3666,19 @@ void prim_match(EvalState & state, const Pos & pos, Value * * args, Value & v)
} catch (std::regex_error &e) { } catch (std::regex_error &e) {
if (e.code() == std::regex_constants::error_space) { if (e.code() == std::regex_constants::error_space) {
// limit is _GLIBCXX_REGEX_STATE_LIMIT for libstdc++ // limit is _GLIBCXX_REGEX_STATE_LIMIT for libstdc++
state.debug_throw(EvalError({ auto e = EvalError({
.msg = hintfmt("memory limit exceeded by regular expression '%s'", re), .msg = hintfmt("memory limit exceeded by regular expression '%s'", re),
.errPos = pos .errPos = pos
})); });
state.debugLastTrace(e);
throw e;
} else { } else {
state.debug_throw(EvalError({ auto e = EvalError({
.msg = hintfmt("invalid regular expression '%s'", re), .msg = hintfmt("invalid regular expression '%s'", re),
.errPos = pos .errPos = pos
})); });
state.debugLastTrace(e);
throw e;
} }
} }
} }
@ -3616,15 +3775,19 @@ void prim_split(EvalState & state, const Pos & pos, Value * * args, Value & v)
} catch (std::regex_error &e) { } catch (std::regex_error &e) {
if (e.code() == std::regex_constants::error_space) { if (e.code() == std::regex_constants::error_space) {
// limit is _GLIBCXX_REGEX_STATE_LIMIT for libstdc++ // limit is _GLIBCXX_REGEX_STATE_LIMIT for libstdc++
state.debug_throw(EvalError({ auto e = EvalError({
.msg = hintfmt("memory limit exceeded by regular expression '%s'", re), .msg = hintfmt("memory limit exceeded by regular expression '%s'", re),
.errPos = pos .errPos = pos
})); });
state.debugLastTrace(e);
throw e;
} else { } else {
state.debug_throw(EvalError({ auto e = EvalError({
.msg = hintfmt("invalid regular expression '%s'", re), .msg = hintfmt("invalid regular expression '%s'", re),
.errPos = pos .errPos = pos
})); });
state.debugLastTrace(e);
throw e;
} }
} }
} }
@ -3701,10 +3864,14 @@ static void prim_replaceStrings(EvalState & state, const Pos & pos, Value * * ar
state.forceList(*args[0], pos); state.forceList(*args[0], pos);
state.forceList(*args[1], pos); state.forceList(*args[1], pos);
if (args[0]->listSize() != args[1]->listSize()) if (args[0]->listSize() != args[1]->listSize())
state.debug_throw(EvalError({ {
auto e = EvalError({
.msg = hintfmt("'from' and 'to' arguments to 'replaceStrings' have different lengths"), .msg = hintfmt("'from' and 'to' arguments to 'replaceStrings' have different lengths"),
.errPos = pos .errPos = pos
})); });
state.debugLastTrace(e);
throw e;
}
std::vector<std::string> from; std::vector<std::string> from;
from.reserve(args[0]->listSize()); from.reserve(args[0]->listSize());

View file

@ -108,16 +108,25 @@ static void fetchTree(
if (auto aType = args[0]->attrs->get(state.sType)) { if (auto aType = args[0]->attrs->get(state.sType)) {
if (type) if (type)
state.debug_throw(EvalError({ {
auto e = EvalError({
.msg = hintfmt("unexpected attribute 'type'"), .msg = hintfmt("unexpected attribute 'type'"),
.errPos = pos .errPos = pos
})); });
state.debugLastTrace(e);
throw e;
}
type = state.forceStringNoCtx(*aType->value, *aType->pos); type = state.forceStringNoCtx(*aType->value, *aType->pos);
} else if (!type) } else if (!type)
state.debug_throw(EvalError({ {
auto e = EvalError({
.msg = hintfmt("attribute 'type' is missing in call to 'fetchTree'"), .msg = hintfmt("attribute 'type' is missing in call to 'fetchTree'"),
.errPos = pos .errPos = pos
})); });
state.debugLastTrace(e);
throw e;
}
attrs.emplace("type", type.value()); attrs.emplace("type", type.value());
@ -138,16 +147,24 @@ static void fetchTree(
else if (attr.value->type() == nInt) else if (attr.value->type() == nInt)
attrs.emplace(attr.name, uint64_t(attr.value->integer)); attrs.emplace(attr.name, uint64_t(attr.value->integer));
else else
state.debug_throw(TypeError("fetchTree argument '%s' is %s while a string, Boolean or integer is expected", {
attr.name, showType(*attr.value))); auto e = TypeError("fetchTree argument '%s' is %s while a string, Boolean or integer is expected",
attr.name, showType(*attr.value));
state.debugLastTrace(e);
throw e;
}
} }
if (!params.allowNameArgument) if (!params.allowNameArgument)
if (auto nameIter = attrs.find("name"); nameIter != attrs.end()) if (auto nameIter = attrs.find("name"); nameIter != attrs.end())
state.debug_throw(EvalError({ {
auto e = EvalError({
.msg = hintfmt("attribute 'name' isnt supported in call to 'fetchTree'"), .msg = hintfmt("attribute 'name' isnt supported in call to 'fetchTree'"),
.errPos = pos .errPos = pos
})); });
state.debugLastTrace(e);
throw e;
}
input = fetchers::Input::fromAttrs(std::move(attrs)); input = fetchers::Input::fromAttrs(std::move(attrs));
} else { } else {
@ -167,7 +184,11 @@ static void fetchTree(
input = lookupInRegistries(state.store, input).first; input = lookupInRegistries(state.store, input).first;
if (evalSettings.pureEval && !input.isLocked()) if (evalSettings.pureEval && !input.isLocked())
state.debug_throw(EvalError("in pure evaluation mode, 'fetchTree' requires a locked input, at %s", pos)); {
auto e = EvalError("in pure evaluation mode, 'fetchTree' requires a locked input, at %s", pos);
state.debugLastTrace(e);
throw e;
}
auto [tree, input2] = input.fetch(state.store); auto [tree, input2] = input.fetch(state.store);
@ -205,18 +226,25 @@ static void fetch(EvalState & state, const Pos & pos, Value * * args, Value & v,
expectedHash = newHashAllowEmpty(state.forceStringNoCtx(*attr.value, *attr.pos), htSHA256); expectedHash = newHashAllowEmpty(state.forceStringNoCtx(*attr.value, *attr.pos), htSHA256);
else if (n == "name") else if (n == "name")
name = state.forceStringNoCtx(*attr.value, *attr.pos); name = state.forceStringNoCtx(*attr.value, *attr.pos);
else else {
state.debug_throw(EvalError({ auto e = EvalError({
.msg = hintfmt("unsupported argument '%s' to '%s'", attr.name, who), .msg = hintfmt("unsupported argument '%s' to '%s'", attr.name, who),
.errPos = *attr.pos .errPos = *attr.pos
})); });
state.debugLastTrace(e);
throw e;
} }
}
if (!url) if (!url)
state.debug_throw(EvalError({ {
auto e = EvalError({
.msg = hintfmt("'url' argument required"), .msg = hintfmt("'url' argument required"),
.errPos = pos .errPos = pos
})); });
state.debugLastTrace(e);
throw e;
}
} else } else
url = state.forceStringNoCtx(*args[0], pos); url = state.forceStringNoCtx(*args[0], pos);
@ -228,7 +256,11 @@ static void fetch(EvalState & state, const Pos & pos, Value * * args, Value & v,
name = baseNameOf(*url); name = baseNameOf(*url);
if (evalSettings.pureEval && !expectedHash) if (evalSettings.pureEval && !expectedHash)
state.debug_throw(EvalError("in pure evaluation mode, '%s' requires a 'sha256' argument", who)); {
auto e = EvalError("in pure evaluation mode, '%s' requires a 'sha256' argument", who);
state.debugLastTrace(e);
throw e;
}
// early exit if pinned and already in the store // early exit if pinned and already in the store
if (expectedHash && expectedHash->type == htSHA256) { if (expectedHash && expectedHash->type == htSHA256) {
@ -255,8 +287,12 @@ static void fetch(EvalState & state, const Pos & pos, Value * * args, Value & v,
? state.store->queryPathInfo(storePath)->narHash ? state.store->queryPathInfo(storePath)->narHash
: hashFile(htSHA256, state.store->toRealPath(storePath)); : hashFile(htSHA256, state.store->toRealPath(storePath));
if (hash != *expectedHash) if (hash != *expectedHash)
state.debug_throw(EvalError((unsigned int) 102, "hash mismatch in file downloaded from '%s':\n specified: %s\n got: %s", {
*url, expectedHash->to_string(Base32, true), hash.to_string(Base32, true))); auto e = EvalError((unsigned int) 102, "hash mismatch in file downloaded from '%s':\n specified: %s\n got: %s",
*url, expectedHash->to_string(Base32, true), hash.to_string(Base32, true));
state.debugLastTrace(e);
throw e;
}
} }
state.allowAndSetStorePathString(storePath, v); state.allowAndSetStorePathString(storePath, v);

View file

@ -85,7 +85,8 @@ void printValueAsJSON(EvalState & state, bool strict,
.errPos = v.determinePos(pos) .errPos = v.determinePos(pos)
}); });
e.addTrace(pos, hintfmt("message for the trace")); e.addTrace(pos, hintfmt("message for the trace"));
state.debug_throw(e); state.debugLastTrace(e);
throw e;
} }
} }
@ -99,7 +100,9 @@ void printValueAsJSON(EvalState & state, bool strict,
void ExternalValueBase::printValueAsJSON(EvalState & state, bool strict, void ExternalValueBase::printValueAsJSON(EvalState & state, bool strict,
JSONPlaceholder & out, PathSet & context) const JSONPlaceholder & out, PathSet & context) const
{ {
state.debug_throw(TypeError("cannot convert %1% to JSON", showType())); auto e = TypeError("cannot convert %1% to JSON", showType());
state.debugLastTrace(e);
throw e;
} }