add pos to errorinfo, remove from hints

This commit is contained in:
Ben Burdette 2020-05-08 18:18:28 -06:00
parent 1b801cec40
commit 55eb717148
13 changed files with 507 additions and 194 deletions

View file

@ -126,17 +126,28 @@ int main()
// Error with previous and next lines of code. // Error with previous and next lines of code.
logError( logError(
ErrorInfo { .name = "error name", ErrorInfo { .name = "error name",
.description = "error description", .description = "error with code lines",
.hint = hintfmt("this hint has %1% templated %2%!!", .hint = hintfmt("this hint has %1% templated %2%!!",
"yellow", "yellow",
"values"), "values"),
.nixCode = NixCode { .nixCode = NixCode {
.errPos = Pos(problem_file, 40, 13), .errPos = Pos(problem_file, 40, 13),
.prevLineOfCode = std::optional("previous line of code"), .prevLineOfCode = "previous line of code",
.errLineOfCode = "this is the problem line of code", .errLineOfCode = "this is the problem line of code",
.nextLineOfCode = std::optional("next line of code"), .nextLineOfCode = "next line of code",
}}); }});
// Error without lines of code.
logError(
ErrorInfo { .name = "error name",
.description = "error without any code lines.",
.hint = hintfmt("this hint has %1% templated %2%!!",
"yellow",
"values"),
.nixCode = NixCode {
.errPos = Pos(problem_file, 40, 13)
}});
return 0; return 0;
} }

View file

@ -76,7 +76,12 @@ public:
{ {
auto a = get(name); auto a = get(name);
if (!a) if (!a)
throw Error("attribute '%s' missing, at %s", name, pos); throw Error(
ErrorInfo {
.hint = hintfmt("attribute '%s' missing", name),
.nixCode = NixCode { .errPos = pos }
});
return *a; return *a;
} }

View file

@ -9,7 +9,11 @@ namespace nix {
LocalNoInlineNoReturn(void throwEvalError(const char * s, const Pos & pos)) LocalNoInlineNoReturn(void throwEvalError(const char * s, const Pos & pos))
{ {
throw EvalError(s, pos); throw EvalError(
ErrorInfo {
.hint = hintfmt(s),
.nixCode = NixCode { .errPos = pos }
});
} }
LocalNoInlineNoReturn(void throwTypeError(const char * s, const Value & v)) LocalNoInlineNoReturn(void throwTypeError(const char * s, const Value & v))
@ -20,7 +24,11 @@ LocalNoInlineNoReturn(void throwTypeError(const char * s, const Value & v))
LocalNoInlineNoReturn(void throwTypeError(const char * s, const Value & v, const Pos & pos)) LocalNoInlineNoReturn(void throwTypeError(const char * s, const Value & v, const Pos & pos))
{ {
throw TypeError(s, showType(v), pos); throw TypeError(
ErrorInfo {
.hint = hintfmt(s, showType(v)),
.nixCode = NixCode { .errPos = pos }
});
} }
@ -43,7 +51,7 @@ void EvalState::forceValue(Value & v, const Pos & pos)
else if (v.type == tApp) else if (v.type == tApp)
callFunction(*v.app.left, *v.app.right, v, noPos); callFunction(*v.app.left, *v.app.right, v, noPos);
else if (v.type == tBlackhole) else if (v.type == tBlackhole)
throwEvalError("infinite recursion encountered, at %1%", pos); throwEvalError("infinite recursion encountered", pos);
} }
@ -59,7 +67,7 @@ inline void EvalState::forceAttrs(Value & v, const Pos & pos)
{ {
forceValue(v); forceValue(v);
if (v.type != tAttrs) if (v.type != tAttrs)
throwTypeError("value is %1% while a set was expected, at %2%", v, pos); throwTypeError("value is %1% while a set was expected", v, pos);
} }
@ -75,7 +83,7 @@ inline void EvalState::forceList(Value & v, const Pos & pos)
{ {
forceValue(v); forceValue(v);
if (!v.isList()) if (!v.isList())
throwTypeError("value is %1% while a list was expected, at %2%", v, pos); throwTypeError("value is %1% while a list was expected", v, pos);
} }
/* Note: Various places expect the allocated memory to be zeroed. */ /* Note: Various places expect the allocated memory to be zeroed. */

View file

@ -498,7 +498,11 @@ LocalNoInlineNoReturn(void throwEvalError(const char * s, const string & s2))
LocalNoInlineNoReturn(void throwEvalError(const char * s, const string & s2, const Pos & pos)) LocalNoInlineNoReturn(void throwEvalError(const char * s, const string & s2, const Pos & pos))
{ {
throw EvalError(s, s2, pos); throw EvalError(
ErrorInfo {
.hint = hintfmt(s, s2),
.nixCode = NixCode { .errPos = pos }
});
} }
LocalNoInlineNoReturn(void throwEvalError(const char * s, const string & s2, const string & s3)) LocalNoInlineNoReturn(void throwEvalError(const char * s, const string & s2, const string & s3))
@ -508,7 +512,11 @@ LocalNoInlineNoReturn(void throwEvalError(const char * s, const string & s2, con
LocalNoInlineNoReturn(void throwEvalError(const char * s, const string & s2, const string & s3, const Pos & pos)) LocalNoInlineNoReturn(void throwEvalError(const char * s, const string & s2, const string & s3, const Pos & pos))
{ {
throw EvalError(s, s2, s3, pos); throw EvalError(
ErrorInfo {
.hint = hintfmt(s, s2, s3),
.nixCode = NixCode { .errPos = pos }
});
} }
LocalNoInlineNoReturn(void throwEvalError(const char * s, const Symbol & sym, const Pos & p1, const Pos & p2)) LocalNoInlineNoReturn(void throwEvalError(const char * s, const Symbol & sym, const Pos & p1, const Pos & p2))
@ -518,7 +526,11 @@ LocalNoInlineNoReturn(void throwEvalError(const char * s, const Symbol & sym, co
LocalNoInlineNoReturn(void throwTypeError(const char * s, const Pos & pos)) LocalNoInlineNoReturn(void throwTypeError(const char * s, const Pos & pos))
{ {
throw TypeError(s, pos); throw TypeError(
ErrorInfo {
.hint = hintfmt(s),
.nixCode = NixCode { .errPos = pos }
});
} }
LocalNoInlineNoReturn(void throwTypeError(const char * s, const string & s1)) LocalNoInlineNoReturn(void throwTypeError(const char * s, const string & s1))
@ -528,17 +540,29 @@ LocalNoInlineNoReturn(void throwTypeError(const char * s, const string & s1))
LocalNoInlineNoReturn(void throwTypeError(const char * s, const ExprLambda & fun, const Symbol & s2, const Pos & pos)) LocalNoInlineNoReturn(void throwTypeError(const char * s, const ExprLambda & fun, const Symbol & s2, const Pos & pos))
{ {
throw TypeError(s, fun.showNamePos(), s2, pos); throw TypeError(
ErrorInfo {
.hint = hintfmt(s, fun.showNamePos(), s2),
.nixCode = NixCode { .errPos = pos }
});
} }
LocalNoInlineNoReturn(void throwAssertionError(const char * s, const string & s1, const Pos & pos)) LocalNoInlineNoReturn(void throwAssertionError(const char * s, const string & s1, const Pos & pos))
{ {
throw AssertionError(s, s1, pos); throw AssertionError(
ErrorInfo {
.hint = hintfmt(s, s1),
.nixCode = NixCode { .errPos = pos }
});
} }
LocalNoInlineNoReturn(void throwUndefinedVarError(const char * s, const string & s1, const Pos & pos)) LocalNoInlineNoReturn(void throwUndefinedVarError(const char * s, const string & s1, const Pos & pos))
{ {
throw UndefinedVarError(s, s1, pos); throw UndefinedVarError(
ErrorInfo {
.hint = hintfmt(s, s1),
.nixCode = NixCode { .errPos = pos }
});
} }
LocalNoInline(void addErrorPrefix(Error & e, const char * s, const string & s2)) LocalNoInline(void addErrorPrefix(Error & e, const char * s, const string & s2))
@ -804,7 +828,7 @@ inline bool EvalState::evalBool(Env & env, Expr * e, const Pos & pos)
Value v; Value v;
e->eval(*this, env, v); e->eval(*this, env, v);
if (v.type != tBool) if (v.type != tBool)
throwTypeError("value is %1% while a Boolean was expected, at %2%", v, pos); throwTypeError("value is %1% while a Boolean was expected", v, pos);
return v.boolean; return v.boolean;
} }
@ -1006,7 +1030,7 @@ void ExprSelect::eval(EvalState & state, Env & env, Value & v)
} else { } else {
state.forceAttrs(*vAttrs, pos); state.forceAttrs(*vAttrs, pos);
if ((j = vAttrs->attrs->find(name)) == vAttrs->attrs->end()) if ((j = vAttrs->attrs->find(name)) == vAttrs->attrs->end())
throwEvalError("attribute '%1%' missing, at %2%", name, pos); throwEvalError("attribute '%1%' missing", name, pos);
} }
vAttrs = j->value; vAttrs = j->value;
pos2 = j->pos; pos2 = j->pos;
@ -1132,7 +1156,7 @@ void EvalState::callFunction(Value & fun, Value & arg, Value & v, const Pos & po
} }
if (fun.type != tLambda) if (fun.type != tLambda)
throwTypeError("attempt to call something which is not a function but %1%, at %2%", fun, pos); throwTypeError("attempt to call something which is not a function but %1%", fun, pos);
ExprLambda & lambda(*fun.lambda.fun); ExprLambda & lambda(*fun.lambda.fun);
@ -1160,7 +1184,7 @@ void EvalState::callFunction(Value & fun, Value & arg, Value & v, const Pos & po
for (auto & i : lambda.formals->formals) { for (auto & i : lambda.formals->formals) {
Bindings::iterator j = arg.attrs->find(i.name); Bindings::iterator j = arg.attrs->find(i.name);
if (j == arg.attrs->end()) { if (j == arg.attrs->end()) {
if (!i.def) throwTypeError("%1% called without required argument '%2%', at %3%", if (!i.def) throwTypeError("%1% called without required argument '%2%'",
lambda, i.name, pos); lambda, i.name, pos);
env2.values[displ++] = i.def->maybeThunk(*this, env2); env2.values[displ++] = i.def->maybeThunk(*this, env2);
} else { } else {
@ -1176,7 +1200,7 @@ void EvalState::callFunction(Value & fun, Value & arg, Value & v, const Pos & po
user. */ user. */
for (auto & i : *arg.attrs) for (auto & i : *arg.attrs)
if (lambda.formals->argNames.find(i.name) == lambda.formals->argNames.end()) if (lambda.formals->argNames.find(i.name) == lambda.formals->argNames.end())
throwTypeError("%1% called with unexpected argument '%2%', at %3%", lambda, i.name, pos); throwTypeError("%1% called with unexpected argument '%2%'", lambda, i.name, pos);
abort(); // can't happen abort(); // can't happen
} }
} }
@ -1417,14 +1441,14 @@ void ExprConcatStrings::eval(EvalState & state, Env & env, Value & v)
nf = n; nf = n;
nf += vTmp.fpoint; nf += vTmp.fpoint;
} else } else
throwEvalError("cannot add %1% to an integer, at %2%", showType(vTmp), pos); throwEvalError("cannot add %1% to an integer", showType(vTmp), pos);
} else if (firstType == tFloat) { } else if (firstType == tFloat) {
if (vTmp.type == tInt) { if (vTmp.type == tInt) {
nf += vTmp.integer; nf += vTmp.integer;
} else if (vTmp.type == tFloat) { } else if (vTmp.type == tFloat) {
nf += vTmp.fpoint; nf += vTmp.fpoint;
} else } else
throwEvalError("cannot add %1% to a float, at %2%", showType(vTmp), pos); throwEvalError("cannot add %1% to a float", showType(vTmp), pos);
} else } else
s << state.coerceToString(pos, vTmp, context, false, firstType == tString); s << state.coerceToString(pos, vTmp, context, false, firstType == tString);
} }
@ -1435,7 +1459,7 @@ void ExprConcatStrings::eval(EvalState & state, Env & env, Value & v)
mkFloat(v, nf); mkFloat(v, nf);
else if (firstType == tPath) { else if (firstType == tPath) {
if (!context.empty()) if (!context.empty())
throwEvalError("a string that refers to a store path cannot be appended to a path, at %1%", pos); throwEvalError("a string that refers to a store path cannot be appended to a path", pos);
auto path = canonPath(s.str()); auto path = canonPath(s.str());
mkPath(v, path.c_str()); mkPath(v, path.c_str());
} else } else
@ -1484,7 +1508,7 @@ NixInt EvalState::forceInt(Value & v, const Pos & pos)
{ {
forceValue(v, pos); forceValue(v, pos);
if (v.type != tInt) if (v.type != tInt)
throwTypeError("value is %1% while an integer was expected, at %2%", v, pos); throwTypeError("value is %1% while an integer was expected", v, pos);
return v.integer; return v.integer;
} }
@ -1495,7 +1519,7 @@ NixFloat EvalState::forceFloat(Value & v, const Pos & pos)
if (v.type == tInt) if (v.type == tInt)
return v.integer; return v.integer;
else if (v.type != tFloat) else if (v.type != tFloat)
throwTypeError("value is %1% while a float was expected, at %2%", v, pos); throwTypeError("value is %1% while a float was expected", v, pos);
return v.fpoint; return v.fpoint;
} }
@ -1504,7 +1528,7 @@ bool EvalState::forceBool(Value & v, const Pos & pos)
{ {
forceValue(v); forceValue(v);
if (v.type != tBool) if (v.type != tBool)
throwTypeError("value is %1% while a Boolean was expected, at %2%", v, pos); throwTypeError("value is %1% while a Boolean was expected", v, pos);
return v.boolean; return v.boolean;
} }
@ -1519,7 +1543,7 @@ void EvalState::forceFunction(Value & v, const Pos & pos)
{ {
forceValue(v); forceValue(v);
if (v.type != tLambda && v.type != tPrimOp && v.type != tPrimOpApp && !isFunctor(v)) if (v.type != tLambda && v.type != tPrimOp && v.type != tPrimOpApp && !isFunctor(v))
throwTypeError("value is %1% while a function was expected, at %2%", v, pos); throwTypeError("value is %1% while a function was expected", v, pos);
} }
@ -1528,7 +1552,7 @@ string EvalState::forceString(Value & v, const Pos & pos)
forceValue(v, pos); forceValue(v, pos);
if (v.type != tString) { if (v.type != tString) {
if (pos) if (pos)
throwTypeError("value is %1% while a string was expected, at %2%", v, pos); throwTypeError("value is %1% while a string was expected", v, pos);
else else
throwTypeError("value is %1% while a string was expected", v); throwTypeError("value is %1% while a string was expected", v);
} }
@ -1557,7 +1581,7 @@ string EvalState::forceStringNoCtx(Value & v, const Pos & pos)
string s = forceString(v, pos); string s = forceString(v, pos);
if (v.string.context) { if (v.string.context) {
if (pos) if (pos)
throwEvalError("the string '%1%' is not allowed to refer to a store path (such as '%2%'), at %3%", throwEvalError("the string '%1%' is not allowed to refer to a store path (such as '%2%')",
v.string.s, v.string.context[0], pos); v.string.s, v.string.context[0], pos);
else else
throwEvalError("the string '%1%' is not allowed to refer to a store path (such as '%2%')", throwEvalError("the string '%1%' is not allowed to refer to a store path (such as '%2%')",
@ -1614,7 +1638,7 @@ string EvalState::coerceToString(const Pos & pos, Value & v, PathSet & context,
return *maybeString; return *maybeString;
} }
auto i = v.attrs->find(sOutPath); auto i = v.attrs->find(sOutPath);
if (i == v.attrs->end()) throwTypeError("cannot coerce a set to a string, at %1%", pos); if (i == v.attrs->end()) throwTypeError("cannot coerce a set to a string", pos);
return coerceToString(pos, *i->value, context, coerceMore, copyToStore); return coerceToString(pos, *i->value, context, coerceMore, copyToStore);
} }
@ -1645,7 +1669,7 @@ string EvalState::coerceToString(const Pos & pos, Value & v, PathSet & context,
} }
} }
throwTypeError("cannot coerce %1% to a string, at %2%", v, pos); throwTypeError("cannot coerce %1% to a string", v, pos);
} }
@ -1676,7 +1700,7 @@ Path EvalState::coerceToPath(const Pos & pos, Value & v, PathSet & context)
{ {
string path = coerceToString(pos, v, context, false, false); string path = coerceToString(pos, v, context, false, false);
if (path == "" || path[0] != '/') if (path == "" || path[0] != '/')
throwEvalError("string '%1%' doesn't represent an absolute path, at %2%", path, pos); throwEvalError("string '%1%' doesn't represent an absolute path", path, pos);
return path; return path;
} }
@ -1883,7 +1907,11 @@ void EvalState::printStats()
string ExternalValueBase::coerceToString(const Pos & pos, PathSet & context, bool copyMore, bool copyToStore) const string ExternalValueBase::coerceToString(const Pos & pos, PathSet & context, bool copyMore, bool copyToStore) const
{ {
throw TypeError("cannot coerce %1% to a string, at %2%", showType(), pos); throw TypeError(
ErrorInfo {
.hint = hintfmt("cannot coerce %1% to a string", showType()),
.nixCode = NixCode { .errPos = pos }
});
} }

View file

@ -404,7 +404,12 @@ expr_simple
| URI { | URI {
static bool noURLLiterals = settings.isExperimentalFeatureEnabled("no-url-literals"); static bool noURLLiterals = settings.isExperimentalFeatureEnabled("no-url-literals");
if (noURLLiterals) if (noURLLiterals)
throw ParseError("URL literals are disabled, at %s", CUR_POS); throw ParseError(
ErrorInfo {
.hint = hintfmt("URL literals are disabled"),
.nixCode = NixCode { .errPos = CUR_POS }
});
$$ = new ExprString(data->symbols.create($1)); $$ = new ExprString(data->symbols.create($1));
} }
| '(' expr ')' { $$ = $2; } | '(' expr ')' { $$ = $2; }
@ -669,10 +674,12 @@ Path EvalState::findFile(SearchPath & searchPath, const string & path, const Pos
Path res = r.second + suffix; Path res = r.second + suffix;
if (pathExists(res)) return canonPath(res); if (pathExists(res)) return canonPath(res);
} }
string f =
"file '%1%' was not found in the Nix search path (add it using $NIX_PATH or -I)" throw ThrownError(
+ string(pos ? ", at %2%" : ""); ErrorInfo {
throw ThrownError(f, path, pos); .hint = hintfmt("file '%1%' was not found in the Nix search path (add it using $NIX_PATH or -I)", path),
.nixCode = NixCode { .errPos = pos }
});
} }

View file

@ -94,8 +94,13 @@ static void prim_scopedImport(EvalState & state, const Pos & pos, Value * * args
try { try {
state.realiseContext(context); state.realiseContext(context);
} catch (InvalidPathError & e) { } catch (InvalidPathError & e) {
throw EvalError("cannot import '%1%', since path '%2%' is not valid, at %3%", throw EvalError(
path, e.path, pos); ErrorInfo {
.hint = hintfmt("cannot import '%1%', since path '%2%' is not valid",
path, e.path),
.nixCode = NixCode { .errPos = pos }
});
} }
Path realPath = state.checkSourcePath(state.toRealPath(path, context)); Path realPath = state.checkSourcePath(state.toRealPath(path, context));
@ -171,8 +176,13 @@ void prim_importNative(EvalState & state, const Pos & pos, Value * * args, Value
try { try {
state.realiseContext(context); state.realiseContext(context);
} catch (InvalidPathError & e) { } catch (InvalidPathError & e) {
throw EvalError("cannot import '%1%', since path '%2%' is not valid, at %3%" throw EvalError(
, path, e.path, pos); ErrorInfo {
.hint = hintfmt(
"cannot import '%1%', since path '%2%' is not valid",
path, e.path),
.nixCode = NixCode { .errPos = pos }
});
} }
path = state.checkSourcePath(path); path = state.checkSourcePath(path);
@ -207,7 +217,11 @@ 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) {
throw EvalError("at least one argument to 'exec' required, at %1%", pos); throw EvalError(
ErrorInfo {
.hint = hintfmt("at least one argument to 'exec' required"),
.nixCode = NixCode { .errPos = pos }
});
} }
PathSet context; PathSet context;
auto program = state.coerceToString(pos, *elems[0], context, false, false); auto program = state.coerceToString(pos, *elems[0], context, false, false);
@ -218,9 +232,12 @@ void prim_exec(EvalState & state, const Pos & pos, Value * * args, Value & v)
try { try {
state.realiseContext(context); state.realiseContext(context);
} catch (InvalidPathError & e) { } catch (InvalidPathError & e) {
throw EvalError("cannot execute '%1%', since path '%2%' is not valid, at %3%" throw EvalError(
, program, e.path, pos); ErrorInfo {
} .hint = hintfmt("cannot execute '%1%', since path '%2%' is not valid"
, program, e.path),
.nixCode = NixCode { .errPos = pos }
});}
auto output = runProgram(program, true, commandArgs); auto output = runProgram(program, true, commandArgs);
Expr * parsed; Expr * parsed;
@ -371,7 +388,11 @@ static void prim_genericClosure(EvalState & state, const Pos & pos, Value * * ar
Bindings::iterator startSet = Bindings::iterator startSet =
args[0]->attrs->find(state.symbols.create("startSet")); args[0]->attrs->find(state.symbols.create("startSet"));
if (startSet == args[0]->attrs->end()) if (startSet == args[0]->attrs->end())
throw EvalError("attribute 'startSet' required, at %1%", pos); throw EvalError(
ErrorInfo {
.hint = hintfmt("attribute 'startSet' required"),
.nixCode = NixCode { .errPos = pos }
});
state.forceList(*startSet->value, pos); state.forceList(*startSet->value, pos);
ValueList workSet; ValueList workSet;
@ -382,7 +403,11 @@ static void prim_genericClosure(EvalState & state, const Pos & pos, Value * * ar
Bindings::iterator op = Bindings::iterator op =
args[0]->attrs->find(state.symbols.create("operator")); args[0]->attrs->find(state.symbols.create("operator"));
if (op == args[0]->attrs->end()) if (op == args[0]->attrs->end())
throw EvalError("attribute 'operator' required, at %1%", pos); throw EvalError(
ErrorInfo {
.hint = hintfmt("attribute 'operator' required"),
.nixCode = NixCode { .errPos = pos }
});
state.forceValue(*op->value); state.forceValue(*op->value);
/* Construct the closure by applying the operator to element of /* Construct the closure by applying the operator to element of
@ -401,7 +426,11 @@ static void prim_genericClosure(EvalState & state, const Pos & pos, Value * * ar
Bindings::iterator key = Bindings::iterator key =
e->attrs->find(state.symbols.create("key")); e->attrs->find(state.symbols.create("key"));
if (key == e->attrs->end()) if (key == e->attrs->end())
throw EvalError("attribute 'key' required, at %1%", pos); throw EvalError(
ErrorInfo {
.hint = hintfmt("attribute 'key' required"),
.nixCode = NixCode { .errPos = pos }
});
state.forceValue(*key->value); state.forceValue(*key->value);
if (!doneKeys.insert(key->value).second) continue; if (!doneKeys.insert(key->value).second) continue;
@ -533,7 +562,11 @@ static void prim_derivationStrict(EvalState & state, const Pos & pos, Value * *
/* Figure out the name first (for stack backtraces). */ /* Figure out the name first (for stack backtraces). */
Bindings::iterator attr = args[0]->attrs->find(state.sName); Bindings::iterator attr = args[0]->attrs->find(state.sName);
if (attr == args[0]->attrs->end()) if (attr == args[0]->attrs->end())
throw EvalError("required attribute 'name' missing, at %1%", pos); throw EvalError(
ErrorInfo {
.hint = hintfmt("required attribute 'name' missing"),
.nixCode = NixCode { .errPos = pos }
});
string drvName; string drvName;
Pos & posDrvName(*attr->pos); Pos & posDrvName(*attr->pos);
try { try {
@ -576,25 +609,45 @@ static void prim_derivationStrict(EvalState & state, const Pos & pos, Value * *
auto handleHashMode = [&](const std::string & s) { auto handleHashMode = [&](const std::string & s) {
if (s == "recursive") outputHashRecursive = true; if (s == "recursive") outputHashRecursive = true;
else if (s == "flat") outputHashRecursive = false; else if (s == "flat") outputHashRecursive = false;
else throw EvalError("invalid value '%s' for 'outputHashMode' attribute, at %s", s, posDrvName); else
throw EvalError(
ErrorInfo {
.hint = hintfmt("invalid value '%s' for 'outputHashMode' attribute", s),
.nixCode = NixCode { .errPos = posDrvName }
});
}; };
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())
throw EvalError("duplicate derivation output '%1%', at %2%", j, posDrvName); throw EvalError(
ErrorInfo {
.hint = hintfmt("duplicate derivation output '%1%'", j),
.nixCode = NixCode { .errPos = posDrvName }
});
/* !!! 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")
throw EvalError("invalid derivation output name 'drv', at %1%", posDrvName); throw EvalError(
ErrorInfo {
.hint = hintfmt("invalid derivation output name 'drv'" ),
.nixCode = NixCode { .errPos = posDrvName }
});
outputs.insert(j); outputs.insert(j);
} }
if (outputs.empty()) if (outputs.empty())
throw EvalError("derivation cannot have an empty set of outputs, at %1%", posDrvName); throw EvalError(
ErrorInfo {
.hint = hintfmt("derivation cannot have an empty set of outputs"),
.nixCode = NixCode { .errPos = posDrvName }
});
}; };
try { try {
@ -706,18 +759,37 @@ 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 == "")
throw EvalError("required attribute 'builder' missing, at %1%", posDrvName); throw EvalError(
ErrorInfo {
.hint = hintfmt("required attribute 'builder' missing"),
.nixCode = NixCode { .errPos = posDrvName }
});
if (drv.platform == "") if (drv.platform == "")
throw EvalError("required attribute 'system' missing, at %1%", posDrvName); throw EvalError(
ErrorInfo {
.hint = hintfmt("required attribute 'system' missing"),
.nixCode = NixCode { .errPos = posDrvName }
});
/* Check whether the derivation name is valid. */ /* Check whether the derivation name is valid. */
if (isDerivation(drvName)) if (isDerivation(drvName))
throw EvalError("derivation names are not allowed to end in '%s', at %s", drvExtension, posDrvName); throw EvalError(
ErrorInfo {
.hint = hintfmt("derivation names are not allowed to end in '%s'", drvExtension),
.nixCode = NixCode { .errPos = posDrvName }
});
if (outputHash) { if (outputHash) {
/* Handle fixed-output derivations. */ /* Handle fixed-output derivations. */
if (outputs.size() != 1 || *(outputs.begin()) != "out") if (outputs.size() != 1 || *(outputs.begin()) != "out")
throw Error("multiple outputs are not supported in fixed-output derivations, at %1%", posDrvName); throw Error(
ErrorInfo {
.hint = hintfmt("multiple outputs are not supported in fixed-output derivations"),
.nixCode = NixCode { .errPos = posDrvName }
});
HashType ht = outputHashAlgo.empty() ? htUnknown : parseHashType(outputHashAlgo); HashType ht = outputHashAlgo.empty() ? htUnknown : parseHashType(outputHashAlgo);
Hash h(*outputHash, ht); Hash h(*outputHash, ht);
@ -818,7 +890,11 @@ 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))
throw EvalError("path '%1%' is not in the Nix store, at %2%", path, pos); throw EvalError(
ErrorInfo {
.hint = hintfmt("path '%1%' is not in the Nix store", path),
.nixCode = NixCode { .errPos = pos }
});
Path path2 = state.store->toStorePath(path); Path path2 = state.store->toStorePath(path);
if (!settings.readOnlyMode) if (!settings.readOnlyMode)
state.store->ensurePath(state.store->parseStorePath(path2)); state.store->ensurePath(state.store->parseStorePath(path2));
@ -835,8 +911,12 @@ static void prim_pathExists(EvalState & state, const Pos & pos, Value * * args,
state.realiseContext(context); state.realiseContext(context);
} catch (InvalidPathError & e) { } catch (InvalidPathError & e) {
throw EvalError( throw EvalError(
"cannot check the existence of '%1%', since path '%2%' is not valid, at %3%", ErrorInfo {
path, e.path, pos); .hint = hintfmt(
"cannot check the existence of '%1%', since path '%2%' is not valid",
path, e.path),
.nixCode = NixCode { .errPos = pos }
});
} }
try { try {
@ -879,8 +959,12 @@ static void prim_readFile(EvalState & state, const Pos & pos, Value * * args, Va
try { try {
state.realiseContext(context); state.realiseContext(context);
} catch (InvalidPathError & e) { } catch (InvalidPathError & e) {
throw EvalError("cannot read '%1%', since path '%2%' is not valid, at %3%" throw EvalError(
, path, e.path, pos); ErrorInfo {
.hint = hintfmt("cannot read '%1%', since path '%2%' is not valid"
, path, e.path),
.nixCode = NixCode { .errPos = pos }
});
} }
string s = readFile(state.checkSourcePath(state.toRealPath(path, context))); string s = readFile(state.checkSourcePath(state.toRealPath(path, context)));
if (s.find((char) 0) != string::npos) if (s.find((char) 0) != string::npos)
@ -908,7 +992,11 @@ static void prim_findFile(EvalState & state, const Pos & pos, Value * * args, Va
i = v2.attrs->find(state.symbols.create("path")); i = v2.attrs->find(state.symbols.create("path"));
if (i == v2.attrs->end()) if (i == v2.attrs->end())
throw EvalError("attribute 'path' missing, at %1%", pos); throw EvalError(
ErrorInfo {
.hint = hintfmt("attribute 'path' missing"),
.nixCode = NixCode { .errPos = pos }
});
PathSet context; PathSet context;
string path = state.coerceToString(pos, *i->value, context, false, false); string path = state.coerceToString(pos, *i->value, context, false, false);
@ -916,8 +1004,12 @@ static void prim_findFile(EvalState & state, const Pos & pos, Value * * args, Va
try { try {
state.realiseContext(context); state.realiseContext(context);
} catch (InvalidPathError & e) { } catch (InvalidPathError & e) {
throw EvalError("cannot find '%1%', since path '%2%' is not valid, at %3%", throw EvalError(
path, e.path, pos); ErrorInfo {
.hint = hintfmt("cannot find '%1%', since path '%2%' is not valid",
path, e.path),
.nixCode = NixCode { .errPos = pos }
});
} }
searchPath.emplace_back(prefix, path); searchPath.emplace_back(prefix, path);
@ -934,7 +1026,11 @@ static void prim_hashFile(EvalState & state, const Pos & pos, Value * * args, Va
string type = state.forceStringNoCtx(*args[0], pos); string type = state.forceStringNoCtx(*args[0], pos);
HashType ht = parseHashType(type); HashType ht = parseHashType(type);
if (ht == htUnknown) if (ht == htUnknown)
throw Error("unknown hash type '%1%', at %2%", type, pos); throw Error(
ErrorInfo {
.hint = hintfmt("unknown hash type '%1%'", type),
.nixCode = NixCode { .errPos = pos }
});
PathSet context; // discarded PathSet context; // discarded
Path p = state.coerceToPath(pos, *args[1], context); Path p = state.coerceToPath(pos, *args[1], context);
@ -950,8 +1046,12 @@ static void prim_readDir(EvalState & state, const Pos & pos, Value * * args, Val
try { try {
state.realiseContext(ctx); state.realiseContext(ctx);
} catch (InvalidPathError & e) { } catch (InvalidPathError & e) {
throw EvalError("cannot read '%1%', since path '%2%' is not valid, at %3%", throw EvalError(
path, e.path, pos); ErrorInfo {
.hint = hintfmt("cannot read '%1%', since path '%2%' is not valid",
path, e.path),
.nixCode = NixCode { .errPos = pos }
});
} }
DirEntries entries = readDirectory(state.checkSourcePath(path)); DirEntries entries = readDirectory(state.checkSourcePath(path));
@ -1021,7 +1121,13 @@ 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) != '/')
throw EvalError("in 'toFile': the file '%1%' cannot refer to derivation outputs, at %2%", name, pos); throw EvalError(
ErrorInfo {
.hint = hintfmt(
"in 'toFile': the file '%1%' cannot refer to derivation outputs", \
name),
.nixCode = NixCode { .errPos = pos }
});
refs.insert(state.store->parseStorePath(path)); refs.insert(state.store->parseStorePath(path));
} }
@ -1089,11 +1195,21 @@ static void prim_filterSource(EvalState & state, const Pos & pos, Value * * args
PathSet context; PathSet context;
Path path = state.coerceToPath(pos, *args[1], context); Path path = state.coerceToPath(pos, *args[1], context);
if (!context.empty()) if (!context.empty())
throw EvalError("string '%1%' cannot refer to other paths, at %2%", path, pos); throw EvalError(
ErrorInfo {
.hint = hintfmt("string '%1%' cannot refer to other paths", path),
.nixCode = NixCode { .errPos = pos }
});
state.forceValue(*args[0]); state.forceValue(*args[0]);
if (args[0]->type != tLambda) if (args[0]->type != tLambda)
throw TypeError("first argument in call to 'filterSource' is not a function but %1%, at %2%", showType(*args[0]), pos); throw TypeError(
ErrorInfo {
.hint = hintfmt(
"first argument in call to 'filterSource' is not a function but %1%",
showType(*args[0])),
.nixCode = NixCode { .errPos = pos }
});
addPath(state, pos, std::string(baseNameOf(path)), path, args[0], true, Hash(), v); addPath(state, pos, std::string(baseNameOf(path)), path, args[0], true, Hash(), v);
} }
@ -1113,7 +1229,13 @@ static void prim_path(EvalState & state, const Pos & pos, Value * * args, Value
PathSet context; PathSet context;
path = state.coerceToPath(*attr.pos, *attr.value, context); path = state.coerceToPath(*attr.pos, *attr.value, context);
if (!context.empty()) if (!context.empty())
throw EvalError("string '%1%' cannot refer to other paths, at %2%", path, *attr.pos); throw EvalError(
ErrorInfo {
.hint = hintfmt("string '%1%' cannot refer to other paths",
path),
.nixCode = NixCode { .errPos = *attr.pos }
});
} else if (attr.name == state.sName) } else if (attr.name == state.sName)
name = state.forceStringNoCtx(*attr.value, *attr.pos); name = state.forceStringNoCtx(*attr.value, *attr.pos);
else if (n == "filter") { else if (n == "filter") {
@ -1124,10 +1246,19 @@ static void prim_path(EvalState & state, const Pos & pos, Value * * args, Value
else if (n == "sha256") else if (n == "sha256")
expectedHash = Hash(state.forceStringNoCtx(*attr.value, *attr.pos), htSHA256); expectedHash = Hash(state.forceStringNoCtx(*attr.value, *attr.pos), htSHA256);
else else
throw EvalError("unsupported argument '%1%' to 'addPath', at %2%", attr.name, *attr.pos); throw EvalError(
ErrorInfo {
.hint = hintfmt("unsupported argument '%1%' to 'addPath'",
attr.name),
.nixCode = NixCode { .errPos = *attr.pos }
});
} }
if (path.empty()) if (path.empty())
throw EvalError("'path' required, at %1%", pos); throw EvalError(
ErrorInfo {
.hint = hintfmt("'path' required"),
.nixCode = NixCode { .errPos = pos }
});
if (name.empty()) if (name.empty())
name = baseNameOf(path); name = baseNameOf(path);
@ -1185,7 +1316,12 @@ void prim_getAttr(EvalState & state, const Pos & pos, Value * * args, Value & v)
// !!! Should we create a symbol here or just do a lookup? // !!! Should we create a symbol here or just do a lookup?
Bindings::iterator i = args[1]->attrs->find(state.symbols.create(attr)); Bindings::iterator i = args[1]->attrs->find(state.symbols.create(attr));
if (i == args[1]->attrs->end()) if (i == args[1]->attrs->end())
throw EvalError("attribute '%1%' missing, at %2%", attr, pos); throw EvalError(
ErrorInfo {
.hint = hintfmt("attribute '%1%' missing", attr),
.nixCode = NixCode { .errPos = pos }
});
// !!! add to stack trace? // !!! add to stack trace?
if (state.countCalls && i->pos) state.attrSelects[*i->pos]++; if (state.countCalls && i->pos) state.attrSelects[*i->pos]++;
state.forceValue(*i->value); state.forceValue(*i->value);
@ -1265,14 +1401,23 @@ static void prim_listToAttrs(EvalState & state, const Pos & pos, Value * * args,
Bindings::iterator j = v2.attrs->find(state.sName); Bindings::iterator j = v2.attrs->find(state.sName);
if (j == v2.attrs->end()) if (j == v2.attrs->end())
throw TypeError("'name' attribute missing in a call to 'listToAttrs', at %1%", pos); throw TypeError(
ErrorInfo {
.hint = hintfmt("'name' attribute missing in a call to 'listToAttrs'"),
.nixCode = NixCode { .errPos = pos }
});
string name = state.forceStringNoCtx(*j->value, pos); string name = state.forceStringNoCtx(*j->value, pos);
Symbol sym = state.symbols.create(name); Symbol sym = state.symbols.create(name);
if (seen.insert(sym).second) { if (seen.insert(sym).second) {
Bindings::iterator j2 = v2.attrs->find(state.symbols.create(state.sValue)); Bindings::iterator j2 = v2.attrs->find(state.symbols.create(state.sValue));
if (j2 == v2.attrs->end()) if (j2 == v2.attrs->end())
throw TypeError("'value' attribute missing in a call to 'listToAttrs', at %1%", pos); throw TypeError(
ErrorInfo {
.hint = hintfmt("'value' attribute missing in a call to 'listToAttrs'"),
.nixCode = NixCode { .errPos = pos }
});
v.attrs->push_back(Attr(sym, j2->value, j2->pos)); v.attrs->push_back(Attr(sym, j2->value, j2->pos));
} }
@ -1346,7 +1491,12 @@ static void prim_functionArgs(EvalState & state, const Pos & pos, Value * * args
{ {
state.forceValue(*args[0]); state.forceValue(*args[0]);
if (args[0]->type != tLambda) if (args[0]->type != tLambda)
throw TypeError("'functionArgs' requires a function, at %1%", pos); throw TypeError(
ErrorInfo {
.hint = hintfmt("'functionArgs' requires a function"),
.nixCode = NixCode { .errPos = pos }
});
if (!args[0]->lambda.fun->matchAttrs) { if (!args[0]->lambda.fun->matchAttrs) {
state.mkAttrs(v, 0); state.mkAttrs(v, 0);
@ -1396,7 +1546,12 @@ 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())
throw Error("list index %1% is out of bounds, at %2%", n, pos); throw Error(
ErrorInfo {
.hint = hintfmt("list index %1% is out of bounds", n),
.nixCode = NixCode { .errPos = pos }
});
state.forceValue(*list.listElems()[n]); state.forceValue(*list.listElems()[n]);
v = *list.listElems()[n]; v = *list.listElems()[n];
} }
@ -1423,7 +1578,12 @@ 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)
throw Error("'tail' called on an empty list, at %1%", pos); throw Error(
ErrorInfo {
.hint = hintfmt("'tail' called on an empty list"),
.nixCode = NixCode { .errPos = pos }
});
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)
v.listElems()[n] = args[0]->listElems()[n + 1]; v.listElems()[n] = args[0]->listElems()[n + 1];
@ -1564,7 +1724,12 @@ 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)
throw EvalError("cannot create list of size %1%, at %2%", len, pos); throw EvalError(
ErrorInfo {
.hint = hintfmt("cannot create list of size %1%", len),
.nixCode = NixCode { .errPos = pos }
});
state.mkList(v, len); state.mkList(v, len);
@ -1722,7 +1887,12 @@ static void prim_div(EvalState & state, const Pos & pos, Value * * args, Value &
state.forceValue(*args[1], pos); state.forceValue(*args[1], pos);
NixFloat f2 = state.forceFloat(*args[1], pos); NixFloat f2 = state.forceFloat(*args[1], pos);
if (f2 == 0) throw EvalError("division by zero, at %1%", pos); if (f2 == 0)
throw EvalError(
ErrorInfo {
.hint = hintfmt("division by zero"),
.nixCode = NixCode { .errPos = pos }
});
if (args[0]->type == tFloat || args[1]->type == tFloat) { if (args[0]->type == tFloat || args[1]->type == tFloat) {
mkFloat(v, state.forceFloat(*args[0], pos) / state.forceFloat(*args[1], pos)); mkFloat(v, state.forceFloat(*args[0], pos) / state.forceFloat(*args[1], pos));
@ -1731,7 +1901,12 @@ 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)
throw EvalError("overflow in integer division, at %1%", pos); throw EvalError(
ErrorInfo {
.hint = hintfmt("overflow in integer division"),
.nixCode = NixCode { .errPos = pos }
});
mkInt(v, i1 / i2); mkInt(v, i1 / i2);
} }
} }
@ -1787,7 +1962,12 @@ static void prim_substring(EvalState & state, const Pos & pos, Value * * args, V
PathSet context; PathSet context;
string s = state.coerceToString(pos, *args[2], context); string s = state.coerceToString(pos, *args[2], context);
if (start < 0) throw EvalError("negative start position in 'substring', at %1%", pos); if (start < 0)
throw EvalError(
ErrorInfo {
.hint = hintfmt("negative start position in 'substring'"),
.nixCode = NixCode { .errPos = pos }
});
mkString(v, (unsigned int) start >= s.size() ? "" : string(s, start, len), context); mkString(v, (unsigned int) start >= s.size() ? "" : string(s, start, len), context);
} }
@ -1807,7 +1987,11 @@ static void prim_hashString(EvalState & state, const Pos & pos, Value * * args,
string type = state.forceStringNoCtx(*args[0], pos); string type = state.forceStringNoCtx(*args[0], pos);
HashType ht = parseHashType(type); HashType ht = parseHashType(type);
if (ht == htUnknown) if (ht == htUnknown)
throw Error("unknown hash type '%1%', at %2%", type, pos); throw Error(
ErrorInfo {
.hint = hintfmt("unknown hash type '%1%'", type),
.nixCode = NixCode { .errPos = pos }
});
PathSet context; // discarded PathSet context; // discarded
string s = state.forceString(*args[1], context, pos); string s = state.forceString(*args[1], context, pos);
@ -1850,9 +2034,17 @@ 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++
throw EvalError("memory limit exceeded by regular expression '%s', at %s", re, pos); throw EvalError(
ErrorInfo {
.hint = hintfmt("memory limit exceeded by regular expression '%s'", re),
.nixCode = NixCode { .errPos = pos }
});
} else { } else {
throw EvalError("invalid regular expression '%s', at %s", re, pos); throw EvalError(
ErrorInfo {
.hint = hintfmt("invalid regular expression '%s'", re),
.nixCode = NixCode { .errPos = pos }
});
} }
} }
} }
@ -1917,9 +2109,17 @@ static void prim_split(EvalState & state, const Pos & pos, Value * * args, Value
} 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++
throw EvalError("memory limit exceeded by regular expression '%s', at %s", re, pos); throw EvalError(
ErrorInfo {
.hint = hintfmt("memory limit exceeded by regular expression '%s'", re),
.nixCode = NixCode { .errPos = pos }
});
} else { } else {
throw EvalError("invalid regular expression '%s', at %s", re, pos); throw EvalError(
ErrorInfo {
.hint = hintfmt("invalid regular expression '%s'", re),
.nixCode = NixCode { .errPos = pos }
});
} }
} }
} }
@ -1950,7 +2150,11 @@ 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())
throw EvalError("'from' and 'to' arguments to 'replaceStrings' have different lengths, at %1%", pos); throw EvalError(
ErrorInfo {
.hint = hintfmt("'from' and 'to' arguments to 'replaceStrings' have different lengths"),
.nixCode = NixCode { .errPos = pos }
});
vector<string> from; vector<string> from;
from.reserve(args[0]->listSize()); from.reserve(args[0]->listSize());
@ -2072,11 +2276,20 @@ void fetch(EvalState & state, const Pos & pos, Value * * args, Value & v,
else if (n == "name") else if (n == "name")
request.name = state.forceStringNoCtx(*attr.value, *attr.pos); request.name = state.forceStringNoCtx(*attr.value, *attr.pos);
else else
throw EvalError("unsupported argument '%1%' to '%2%', at %3%", attr.name, who, attr.pos); throw EvalError(
ErrorInfo {
.hint = hintfmt("unsupported argument '%1%' to '%2%'", attr.name, who),
.nixCode = NixCode { .errPos = pos }
});
} }
if (request.uri.empty()) if (request.uri.empty())
throw EvalError("'url' argument required, at %1%", pos); throw EvalError(
ErrorInfo {
.hint = hintfmt("'url' argument required"),
.nixCode = NixCode { .errPos = pos }
});
} else } else
request.uri = state.forceStringNoCtx(*args[0], pos); request.uri = state.forceStringNoCtx(*args[0], pos);

View file

@ -146,7 +146,12 @@ static void prim_appendContext(EvalState & state, const Pos & pos, Value * * arg
auto sAllOutputs = state.symbols.create("allOutputs"); auto sAllOutputs = state.symbols.create("allOutputs");
for (auto & i : *args[1]->attrs) { for (auto & i : *args[1]->attrs) {
if (!state.store->isStorePath(i.name)) if (!state.store->isStorePath(i.name))
throw EvalError("Context key '%s' is not a store path, at %s", i.name, i.pos); throw EvalError(
ErrorInfo {
.hint = hintfmt("Context key '%s' is not a store path", i.name),
.nixCode = NixCode { .errPos = *i.pos }
});
if (!settings.readOnlyMode) if (!settings.readOnlyMode)
state.store->ensurePath(state.store->parseStorePath(i.name)); state.store->ensurePath(state.store->parseStorePath(i.name));
state.forceAttrs(*i.value, *i.pos); state.forceAttrs(*i.value, *i.pos);
@ -160,7 +165,12 @@ static void prim_appendContext(EvalState & state, const Pos & pos, Value * * arg
if (iter != i.value->attrs->end()) { if (iter != i.value->attrs->end()) {
if (state.forceBool(*iter->value, *iter->pos)) { if (state.forceBool(*iter->value, *iter->pos)) {
if (!isDerivation(i.name)) { if (!isDerivation(i.name)) {
throw EvalError("Tried to add all-outputs context of %s, which is not a derivation, to a string, at %s", i.name, i.pos); throw EvalError(
ErrorInfo {
.hint = hintfmt("Tried to add all-outputs context of %s, which is not a derivation, to a string", i.name),
.nixCode = NixCode { .errPos = *i.pos }
});
} }
context.insert("=" + string(i.name)); context.insert("=" + string(i.name));
} }
@ -170,7 +180,11 @@ static void prim_appendContext(EvalState & state, const Pos & pos, Value * * arg
if (iter != i.value->attrs->end()) { if (iter != i.value->attrs->end()) {
state.forceList(*iter->value, *iter->pos); state.forceList(*iter->value, *iter->pos);
if (iter->value->listSize() && !isDerivation(i.name)) { if (iter->value->listSize() && !isDerivation(i.name)) {
throw EvalError("Tried to add derivation output context of %s, which is not a derivation, to a string, at %s", i.name, i.pos); throw EvalError(
ErrorInfo {
.hint = hintfmt("Tried to add derivation output context of %s, which is not a derivation, to a string", i.name),
.nixCode = NixCode { .errPos = *i.pos }
});
} }
for (unsigned int n = 0; n < iter->value->listSize(); ++n) { for (unsigned int n = 0; n < iter->value->listSize(); ++n) {
auto name = state.forceStringNoCtx(*iter->value->listElems()[n], *iter->pos); auto name = state.forceStringNoCtx(*iter->value->listElems()[n], *iter->pos);

View file

@ -217,11 +217,19 @@ static void prim_fetchGit(EvalState & state, const Pos & pos, Value * * args, Va
else if (n == "name") else if (n == "name")
name = state.forceStringNoCtx(*attr.value, *attr.pos); name = state.forceStringNoCtx(*attr.value, *attr.pos);
else else
throw EvalError("unsupported argument '%s' to 'fetchGit', at %s", attr.name, *attr.pos); throw EvalError(
ErrorInfo {
.hint = hintfmt("unsupported argument '%s' to 'fetchGit'", attr.name),
.nixCode = NixCode { .errPos = *attr.pos }
});
} }
if (url.empty()) if (url.empty())
throw EvalError("'url' argument required, at %1%", pos); throw EvalError(
ErrorInfo {
.hint = hintfmt("'url' argument required"),
.nixCode = NixCode { .errPos = pos }
});
} else } else
url = state.coerceToString(pos, *args[0], context, false, false); url = state.coerceToString(pos, *args[0], context, false, false);

View file

@ -187,11 +187,20 @@ static void prim_fetchMercurial(EvalState & state, const Pos & pos, Value * * ar
else if (n == "name") else if (n == "name")
name = state.forceStringNoCtx(*attr.value, *attr.pos); name = state.forceStringNoCtx(*attr.value, *attr.pos);
else else
throw EvalError("unsupported argument '%s' to 'fetchMercurial', at %s", attr.name, *attr.pos); throw EvalError(
ErrorInfo {
.hint = hintfmt("unsupported argument '%s' to 'fetchMercurial'", attr.name),
.nixCode = NixCode { .errPos = *attr.pos }
});
} }
if (url.empty()) if (url.empty())
throw EvalError("'url' argument required, at %1%", pos); throw EvalError(
ErrorInfo {
.hint = hintfmt("'url' argument required"),
.nixCode = NixCode { .errPos = pos }
});
} else } else
url = state.coerceToString(pos, *args[0], context, false, false); url = state.coerceToString(pos, *args[0], context, false, false);

View file

@ -1,4 +1,4 @@
#include "types.hh" #include "error.hh"
#include <iostream> #include <iostream>
#include <optional> #include <optional>
@ -25,31 +25,36 @@ std::ostream& operator<<(std::ostream &os, const hintformat &hf)
string showErrPos(const ErrPos &errPos) string showErrPos(const ErrPos &errPos)
{ {
if (errPos.line > 0) {
if (errPos.column > 0) { if (errPos.column > 0) {
return fmt("(%1%:%2%)", errPos.line, errPos.column); return fmt("(%1%:%2%)", errPos.line, errPos.column);
} else { } else {
return fmt("(%1%)", errPos.line); return fmt("(%1%)", errPos.line);
}; }
}
else {
return "";
}
} }
void printCodeLines(const string &prefix, const NixCode &nixCode) void printCodeLines(std::ostream &out, const string &prefix, const NixCode &nixCode)
{ {
// previous line of code. // previous line of code.
if (nixCode.prevLineOfCode.has_value()) { if (nixCode.prevLineOfCode.has_value()) {
std::cout << fmt("%1% %|2$5d|| %3%", out << fmt("%1% %|2$5d|| %3%",
prefix, prefix,
(nixCode.errPos.line - 1), (nixCode.errPos.line - 1),
*nixCode.prevLineOfCode) *nixCode.prevLineOfCode)
<< std::endl; << std::endl;
} }
// line of code containing the error.%2$+5d% if (nixCode.errLineOfCode.has_value()) {
std::cout << fmt("%1% %|2$5d|| %3%", // line of code containing the error.
out << fmt("%1% %|2$5d|| %3%",
prefix, prefix,
(nixCode.errPos.line), (nixCode.errPos.line),
nixCode.errLineOfCode) *nixCode.errLineOfCode)
<< std::endl; << std::endl;
// error arrows for the column range. // error arrows for the column range.
if (nixCode.errPos.column > 0) { if (nixCode.errPos.column > 0) {
int start = nixCode.errPos.column; int start = nixCode.errPos.column;
@ -60,15 +65,16 @@ void printCodeLines(const string &prefix, const NixCode &nixCode)
std::string arrows("^"); std::string arrows("^");
std::cout << fmt("%1% |%2%" ANSI_RED "%3%" ANSI_NORMAL, out << fmt("%1% |%2%" ANSI_RED "%3%" ANSI_NORMAL,
prefix, prefix,
spaces, spaces,
arrows) << std::endl; arrows) << std::endl;
} }
}
// next line of code. // next line of code.
if (nixCode.nextLineOfCode.has_value()) { if (nixCode.nextLineOfCode.has_value()) {
std::cout << fmt("%1% %|2$5d|| %3%", out << fmt("%1% %|2$5d|| %3%",
prefix, prefix,
(nixCode.errPos.line + 1), (nixCode.errPos.line + 1),
*nixCode.nextLineOfCode) *nixCode.nextLineOfCode)
@ -158,14 +164,10 @@ std::ostream& operator<<(std::ostream &out, const ErrorInfo &einfo)
// filename. // filename.
if (einfo.nixCode.has_value()) { if (einfo.nixCode.has_value()) {
if (einfo.nixCode->errPos.file != "") { if (einfo.nixCode->errPos.file != "") {
string eline = einfo.nixCode->errLineOfCode != "" out << fmt("%1%in file: " ANSI_BLUE "%2% %3%" ANSI_NORMAL,
? string(" ") + showErrPos(einfo.nixCode->errPos)
: "";
out << fmt("%1%in file: " ANSI_BLUE "%2%%3%" ANSI_NORMAL,
prefix, prefix,
einfo.nixCode->errPos.file, einfo.nixCode->errPos.file,
eline) << std::endl; showErrPos(einfo.nixCode->errPos)) << std::endl;
out << prefix << std::endl; out << prefix << std::endl;
} else { } else {
out << fmt("%1%from command line argument", prefix) << std::endl; out << fmt("%1%from command line argument", prefix) << std::endl;
@ -180,8 +182,8 @@ std::ostream& operator<<(std::ostream &out, const ErrorInfo &einfo)
} }
// lines of code. // lines of code.
if (einfo.nixCode.has_value() && einfo.nixCode->errLineOfCode != "") { if (einfo.nixCode.has_value()) {
printCodeLines(prefix, *einfo.nixCode); printCodeLines(out, prefix, *einfo.nixCode);
out << prefix << std::endl; out << prefix << std::endl;
} }

View file

@ -35,10 +35,15 @@ typedef enum {
} Verbosity; } Verbosity;
struct ErrPos { struct ErrPos {
int line; int line = 0;
int column; int column = 0;
string file; string file;
operator bool() const
{
return line != 0;
}
template <class P> template <class P>
ErrPos& operator=(const P &pos) ErrPos& operator=(const P &pos)
{ {
@ -58,7 +63,7 @@ struct ErrPos {
struct NixCode { struct NixCode {
ErrPos errPos; ErrPos errPos;
std::optional<string> prevLineOfCode; std::optional<string> prevLineOfCode;
string errLineOfCode; std::optional<string> errLineOfCode;
std::optional<string> nextLineOfCode; std::optional<string> nextLineOfCode;
}; };

View file

@ -171,7 +171,8 @@ struct JSONLogger : Logger {
json["file"] = ei.nixCode->errPos.file; json["file"] = ei.nixCode->errPos.file;
if (ei.nixCode->prevLineOfCode.has_value()) if (ei.nixCode->prevLineOfCode.has_value())
json["prevLineOfCode"] = *ei.nixCode->prevLineOfCode; json["prevLineOfCode"] = *ei.nixCode->prevLineOfCode;
json["errLineOfCode"] = ei.nixCode->errLineOfCode; if (ei.nixCode->errLineOfCode.has_value())
json["errLineOfCode"] = *ei.nixCode->errLineOfCode;
if (ei.nixCode->nextLineOfCode.has_value()) if (ei.nixCode->nextLineOfCode.has_value())
json["nextLineOfCode"] = *ei.nixCode->nextLineOfCode; json["nextLineOfCode"] = *ei.nixCode->nextLineOfCode;
} }

View file

@ -16,4 +16,6 @@ nix-env --foo 2>&1 | grep "no operation"
nix-env -q --foo 2>&1 | grep "unknown flag" nix-env -q --foo 2>&1 | grep "unknown flag"
# Eval Errors. # Eval Errors.
nix-instantiate --eval -E 'let a = {} // a; in a.foo' 2>&1 | grep "infinite recursion encountered, at .*(string).*:1:15$" eval_res=$(nix-instantiate --eval -E 'let a = {} // a; in a.foo' 2>&1 || true)
echo $eval_res | grep "(string) (1:15)"
echo $eval_res | grep "infinite recursion encountered"