treewide: add evaluator aliases for eval states

this is not necessary in any way, but it will make the following changes
smaller and easier to review. the aliases could also be added piecemeal,
but doing it here lets us lean heavily on our compilers for correctness.

(teacher notes: here the author foreshadows the shape of things to come.
not all names change, and only the names unchanged are those which will,
over time, become ever more unrecognizable. note especially nix/main.cc,
where `state` is not only cloned, but itself changes pointerness. it can
be seen as a nod to the trans community, but more realistically it is no
more than foreshadowing the future where `state` is only seen by proxy.)

Change-Id: I7732025e58df089b7f8e564fc63960cd91729d09
This commit is contained in:
eldritch horrors
2024-12-03 20:38:41 +01:00
parent 473c1bdcab
commit 81559ea8ad
23 changed files with 357 additions and 342 deletions
+11 -10
View File
@@ -198,15 +198,16 @@ static void main_nix_build(std::string programName, Strings argv)
auto store = openStore();
auto evalStore = myArgs.evalStoreUrl ? openStore(*myArgs.evalStoreUrl) : store;
auto state = std::make_unique<EvalState>(myArgs.searchPath, evalStore, store);
state->repair = myArgs.repair;
auto evaluator = std::make_unique<EvalState>(myArgs.searchPath, evalStore, store);
evaluator->repair = myArgs.repair;
auto & state = evaluator;
if (myArgs.repair) buildMode = bmRepair;
auto autoArgs = myArgs.getAutoArgs(*state);
auto autoArgs = myArgs.getAutoArgs(*evaluator);
auto autoArgsWithInNixShell = autoArgs;
if (runEnv) {
auto newArgs = state->buildBindings(autoArgsWithInNixShell->size() + 1);
auto newArgs = evaluator->buildBindings(autoArgsWithInNixShell->size() + 1);
newArgs.alloc("inNixShell").mkBool(true);
for (auto & i : *autoArgs) newArgs.insert(i);
autoArgsWithInNixShell = newArgs.finish();
@@ -236,11 +237,11 @@ static void main_nix_build(std::string programName, Strings argv)
std::vector<std::reference_wrapper<Expr>> exprs;
if (readStdin)
exprs = {state->parseStdin()};
exprs = {evaluator->parseStdin()};
else
for (auto i : left) {
if (fromArgs)
exprs.push_back(state->parseExprFromString(std::move(i), CanonPath::fromCwd()));
exprs.push_back(evaluator->parseExprFromString(std::move(i), CanonPath::fromCwd()));
else {
auto absolute = i;
try {
@@ -252,7 +253,7 @@ static void main_nix_build(std::string programName, Strings argv)
else
/* If we're in a #! script, interpret filenames
relative to the script. */
exprs.push_back(state->parseExprFromFile(resolveExprPath(state->paths.checkSourcePath(lookupFileArg(*state,
exprs.push_back(evaluator->parseExprFromFile(resolveExprPath(evaluator->paths.checkSourcePath(lookupFileArg(*evaluator,
inShebang && !packages ? absPath(i, absPath(dirOf(script))) : i)))));
}
}
@@ -272,7 +273,7 @@ static void main_nix_build(std::string programName, Strings argv)
bool add = false;
if (v.type() == nFunction && v.lambda.fun->hasFormals()) {
for (auto & i : v.lambda.fun->formals->formals) {
if (state->symbols[i.name] == "inNixShell") {
if (evaluator->symbols[i.name] == "inNixShell") {
add = true;
break;
}
@@ -300,7 +301,7 @@ static void main_nix_build(std::string programName, Strings argv)
}
}
state->maybePrintStats();
evaluator->maybePrintStats();
auto buildPaths = [&](const std::vector<DerivedPath> & paths) {
/* Note: we do this even when !printMissing to efficiently
@@ -336,7 +337,7 @@ static void main_nix_build(std::string programName, Strings argv)
if (!shell) {
try {
auto & expr = state->parseExprFromString(
auto & expr = evaluator->parseExprFromString(
"(import <nixpkgs> {}).bashInteractive",
CanonPath::fromCwd());
+89 -96
View File
@@ -511,13 +511,15 @@ static void installDerivations(Globals & globals,
{
debug("installing derivations");
auto state = globals.state;
/* Get the set of user environment elements to be installed. */
DrvInfos newElems, newElemsTmp;
queryInstSources(*globals.state, globals.instSource, args, newElemsTmp, true);
queryInstSources(*state, globals.instSource, args, newElemsTmp, true);
/* If --prebuilt-only is given, filter out source-only packages. */
for (auto & i : newElemsTmp)
if (!globals.prebuiltOnly || isPrebuilt(*globals.state, i))
if (!globals.prebuiltOnly || isPrebuilt(*state, i))
newElems.push_back(i);
StringSet newNames;
@@ -528,7 +530,7 @@ static void installDerivations(Globals & globals,
`java-front-0.9pre15899'). */
if (globals.forceName != "")
i.setName(globals.forceName);
newNames.insert(DrvName(i.queryName(*globals.state)).name);
newNames.insert(DrvName(i.queryName(*state)).name);
}
@@ -540,27 +542,27 @@ static void installDerivations(Globals & globals,
/* Add in the already installed derivations, unless they have
the same name as a to-be-installed element. */
if (!globals.removeAll) {
DrvInfos installedElems = queryInstalled(*globals.state, profile);
DrvInfos installedElems = queryInstalled(*state, profile);
for (auto & i : installedElems) {
DrvName drvName(i.queryName(*globals.state));
DrvName drvName(i.queryName(*state));
if (!globals.preserveInstalled &&
newNames.find(drvName.name) != newNames.end() &&
!keep(*globals.state, i))
printInfo("replacing old '%s'", i.queryName(*globals.state));
!keep(*state, i))
printInfo("replacing old '%s'", i.queryName(*state));
else
allElems.push_back(i);
}
for (auto & i : newElems)
printInfo("installing '%s'", i.queryName(*globals.state));
printInfo("installing '%s'", i.queryName(*state));
}
printMissing(*globals.state, newElems);
printMissing(*state, newElems);
if (globals.dryRun) return;
if (createUserEnv(*globals.state, allElems,
if (createUserEnv(*state, allElems,
profile, settings.envKeepDerivations, lockToken)) break;
}
}
@@ -590,6 +592,8 @@ static void upgradeDerivations(Globals & globals,
{
debug("upgrading derivations");
auto state = globals.state;
/* Upgrade works as follows: we take all currently installed
derivations, and for any derivation matching any selector, look
for a derivation in the input Nix expression that has the same
@@ -598,20 +602,20 @@ static void upgradeDerivations(Globals & globals,
while (true) {
auto lockToken = optimisticLockProfile(globals.profile);
DrvInfos installedElems = queryInstalled(*globals.state, globals.profile);
DrvInfos installedElems = queryInstalled(*state, globals.profile);
/* Fetch all derivations from the input file. */
DrvInfos availElems;
queryInstSources(*globals.state, globals.instSource, args, availElems, false);
queryInstSources(*state, globals.instSource, args, availElems, false);
/* Go through all installed derivations. */
DrvInfos newElems;
for (auto & i : installedElems) {
DrvName drvName(i.queryName(*globals.state));
DrvName drvName(i.queryName(*state));
try {
if (keep(*globals.state, i)) {
if (keep(*state, i)) {
newElems.push_back(i);
continue;
}
@@ -626,9 +630,9 @@ static void upgradeDerivations(Globals & globals,
DrvInfos::iterator bestElem = availElems.end();
std::string bestVersion;
for (auto j = availElems.begin(); j != availElems.end(); ++j) {
if (comparePriorities(*globals.state, i, *j) > 0)
if (comparePriorities(*state, i, *j) > 0)
continue;
DrvName newName(j->queryName(*globals.state));
DrvName newName(j->queryName(*state));
if (newName.name == drvName.name) {
std::strong_ordering d = compareVersions(drvName.version, newName.version);
if ((upgradeType == utLt && d < 0) ||
@@ -638,10 +642,10 @@ static void upgradeDerivations(Globals & globals,
{
std::strong_ordering d2 = std::strong_ordering::less;
if (bestElem != availElems.end()) {
d2 = comparePriorities(*globals.state, *bestElem, *j);
d2 = comparePriorities(*state, *bestElem, *j);
if (d2 == 0) d2 = compareVersions(bestVersion, newName.version);
}
if (d2 < 0 && (!globals.prebuiltOnly || isPrebuilt(*globals.state, *j))) {
if (d2 < 0 && (!globals.prebuiltOnly || isPrebuilt(*state, *j))) {
bestElem = j;
bestVersion = newName.version;
}
@@ -650,27 +654,27 @@ static void upgradeDerivations(Globals & globals,
}
if (bestElem != availElems.end() &&
i.queryOutPath(*globals.state) !=
bestElem->queryOutPath(*globals.state))
i.queryOutPath(*state) !=
bestElem->queryOutPath(*state))
{
const char * action = compareVersions(drvName.version, bestVersion) <= 0
? "upgrading" : "downgrading";
printInfo("%1% '%2%' to '%3%'",
action, i.queryName(*globals.state), bestElem->queryName(*globals.state));
action, i.queryName(*state), bestElem->queryName(*state));
newElems.push_back(*bestElem);
} else newElems.push_back(i);
} catch (Error & e) {
e.addTrace(nullptr, "while trying to find an upgrade for '%s'", i.queryName(*globals.state));
e.addTrace(nullptr, "while trying to find an upgrade for '%s'", i.queryName(*state));
throw;
}
}
printMissing(*globals.state, newElems);
printMissing(*state, newElems);
if (globals.dryRun) return;
if (createUserEnv(*globals.state, newElems,
if (createUserEnv(*state, newElems,
globals.profile, settings.envKeepDerivations, lockToken)) break;
}
}
@@ -714,19 +718,21 @@ static void opSetFlag(Globals & globals, Strings opFlags, Strings opArgs)
std::string flagValue = *arg++;
DrvNames selectors = drvNamesFromArgs(Strings(arg, opArgs.end()));
auto state = globals.state;
while (true) {
std::string lockToken = optimisticLockProfile(globals.profile);
DrvInfos installedElems = queryInstalled(*globals.state, globals.profile);
DrvInfos installedElems = queryInstalled(*state, globals.profile);
/* Update all matching derivations. */
for (auto & i : installedElems) {
DrvName drvName(i.queryName(*globals.state));
DrvName drvName(i.queryName(*state));
for (auto & j : selectors)
if (j.matches(drvName)) {
printInfo("setting flag on '%1%'", i.queryName(*globals.state));
printInfo("setting flag on '%1%'", i.queryName(*state));
j.hits++;
setMetaFlag(*globals.state, i, flagName, flagValue);
setMetaFlag(*state, i, flagName, flagValue);
break;
}
}
@@ -734,7 +740,7 @@ static void opSetFlag(Globals & globals, Strings opFlags, Strings opArgs)
checkSelectorUse(selectors);
/* Write the new user environment. */
if (createUserEnv(*globals.state, installedElems,
if (createUserEnv(*state, installedElems,
globals.profile, settings.envKeepDerivations, lockToken)) break;
}
}
@@ -742,6 +748,8 @@ static void opSetFlag(Globals & globals, Strings opFlags, Strings opArgs)
static void opSet(Globals & globals, Strings opFlags, Strings opArgs)
{
auto state = globals.state;
auto store2 = globals.state->store.dynamic_pointer_cast<LocalFSStore>();
if (!store2) throw Error("--set is not supported for this Nix store");
@@ -752,7 +760,7 @@ static void opSet(Globals & globals, Strings opFlags, Strings opArgs)
}
DrvInfos elems;
queryInstSources(*globals.state, globals.instSource, opArgs, elems, true);
queryInstSources(*state, globals.instSource, opArgs, elems, true);
if (elems.size() != 1)
throw Error("--set requires exactly one derivation");
@@ -762,7 +770,7 @@ static void opSet(Globals & globals, Strings opFlags, Strings opArgs)
if (globals.forceName != "")
drv.setName(globals.forceName);
auto drvPath = drv.queryDrvPath(*globals.state);
auto drvPath = drv.queryDrvPath(*state);
std::vector<DerivedPath> paths {
drvPath
? (DerivedPath) (DerivedPath::Built {
@@ -770,7 +778,7 @@ static void opSet(Globals & globals, Strings opFlags, Strings opArgs)
.outputs = OutputsSpec::All { },
})
: (DerivedPath) (DerivedPath::Opaque {
.path = drv.queryOutPath(*globals.state),
.path = drv.queryOutPath(*state),
}),
};
printMissing(globals.state->store, paths);
@@ -781,7 +789,7 @@ static void opSet(Globals & globals, Strings opFlags, Strings opArgs)
Path generation = createGeneration(
*store2,
globals.profile,
drv.queryOutPath(*globals.state));
drv.queryOutPath(*state));
switchLink(globals.profile, generation);
}
@@ -789,10 +797,12 @@ static void opSet(Globals & globals, Strings opFlags, Strings opArgs)
static void uninstallDerivations(Globals & globals, Strings & selectors,
Path & profile)
{
auto state = globals.state;
while (true) {
auto lockToken = optimisticLockProfile(profile);
DrvInfos workingElems = queryInstalled(*globals.state, profile);
DrvInfos workingElems = queryInstalled(*state, profile);
for (auto & selector : selectors) {
DrvInfos::iterator split = workingElems.begin();
@@ -800,16 +810,16 @@ static void uninstallDerivations(Globals & globals, Strings & selectors,
StorePath selectorStorePath = globals.state->store->followLinksToStorePath(selector);
split = std::partition(
workingElems.begin(), workingElems.end(),
[&selectorStorePath, globals](auto &elem) {
return selectorStorePath != elem.queryOutPath(*globals.state);
[&selectorStorePath, &state](auto &elem) {
return selectorStorePath != elem.queryOutPath(*state);
}
);
} else {
DrvName selectorName(selector);
split = std::partition(
workingElems.begin(), workingElems.end(),
[&selectorName, &globals](auto &elem){
DrvName elemName(elem.queryName(*globals.state));
[&selectorName, &state](auto &elem){
DrvName elemName(elem.queryName(*state));
return !selectorName.matches(elemName);
}
);
@@ -817,14 +827,14 @@ static void uninstallDerivations(Globals & globals, Strings & selectors,
if (split == workingElems.end())
warn("selector '%s' matched no installed derivations", selector);
for (auto removedElem = split; removedElem != workingElems.end(); removedElem++) {
printInfo("uninstalling '%s'", removedElem->queryName(*globals.state));
printInfo("uninstalling '%s'", removedElem->queryName(*state));
}
workingElems.erase(split, workingElems.end());
}
if (globals.dryRun) return;
if (createUserEnv(*globals.state, workingElems,
if (createUserEnv(*state, workingElems,
profile, settings.envKeepDerivations, lockToken)) break;
}
}
@@ -928,7 +938,7 @@ static VersionDiff compareVersionAgainstSet(
}
static void queryJSON(Globals & globals, std::vector<DrvInfo> & elems, bool printOutPath, bool printDrvPath, bool printMeta)
static void queryJSON(EvalState & state, Globals & globals, std::vector<DrvInfo> & elems, bool printOutPath, bool printDrvPath, bool printMeta)
{
using nlohmann::json;
json topObj = json::object();
@@ -937,18 +947,18 @@ static void queryJSON(Globals & globals, std::vector<DrvInfo> & elems, bool prin
if (i.hasFailed()) continue;
auto drvName = DrvName(i.queryName(*globals.state));
auto drvName = DrvName(i.queryName(state));
json &pkgObj = topObj[i.attrPath];
pkgObj = {
{"name", drvName.fullName},
{"pname", drvName.name},
{"version", drvName.version},
{"system", i.querySystem(*globals.state)},
{"outputName", i.queryOutputName(*globals.state)},
{"system", i.querySystem(state)},
{"outputName", i.queryOutputName(state)},
};
{
DrvInfo::Outputs outputs = i.queryOutputs(*globals.state, printOutPath);
DrvInfo::Outputs outputs = i.queryOutputs(state, printOutPath);
json &outputObj = pkgObj["outputs"];
outputObj = json::object();
for (auto & j : outputs) {
@@ -960,37 +970,29 @@ static void queryJSON(Globals & globals, std::vector<DrvInfo> & elems, bool prin
}
if (printDrvPath) {
auto drvPath = i.queryDrvPath(*globals.state);
auto drvPath = i.queryDrvPath(state);
if (drvPath) pkgObj["drvPath"] = globals.state->store->printStorePath(*drvPath);
}
if (printMeta) {
json &metaObj = pkgObj["meta"];
metaObj = json::object();
StringSet metaNames = i.queryMetaNames(*globals.state);
StringSet metaNames = i.queryMetaNames(state);
for (auto & j : metaNames) {
Value * v = i.queryMeta(*globals.state, j);
Value * v = i.queryMeta(state, j);
if (!v) {
printError(
"derivation '%s' has invalid meta attribute '%s'",
i.queryName(*globals.state),
j
);
printError("derivation '%s' has invalid meta attribute '%s'", i.queryName(state), j);
metaObj[j] = nullptr;
} else {
NixStringContext context;
metaObj[j] = printValueAsJSON(*globals.state, true, *v, noPos, context);
metaObj[j] = printValueAsJSON(state, true, *v, noPos, context);
}
}
}
} catch (AssertionError & e) {
printMsg(
lvlTalkative,
"skipping derivation named '%1%' which gives an assertion failure",
i.queryName(*globals.state)
);
printMsg(lvlTalkative, "skipping derivation named '%1%' which gives an assertion failure", i.queryName(state));
} catch (Error & e) {
e.addTrace(nullptr, "while querying the derivation named '%1%'", i.queryName(*globals.state));
e.addTrace(nullptr, "while querying the derivation named '%1%'", i.queryName(state));
throw;
}
}
@@ -1001,6 +1003,7 @@ static void queryJSON(Globals & globals, std::vector<DrvInfo> & elems, bool prin
static void opQuery(Globals & globals, Strings opFlags, Strings opArgs)
{
auto & store { *globals.state->store };
auto state = globals.state;
Strings remaining;
std::string attrPath;
@@ -1049,14 +1052,14 @@ static void opQuery(Globals & globals, Strings opFlags, Strings opArgs)
DrvInfos availElems, installedElems;
if (source == sInstalled || compareVersions || printStatus)
installedElems = queryInstalled(*globals.state, globals.profile);
installedElems = queryInstalled(*state, globals.profile);
if (source == sAvailable || compareVersions)
loadDerivations(*globals.state, *globals.instSource.nixExprPath,
loadDerivations(*state, *globals.instSource.nixExprPath,
globals.instSource.systemFilter, *globals.instSource.autoArgs,
attrPath, availElems);
DrvInfos elems_ = filterBySelector(*globals.state,
DrvInfos elems_ = filterBySelector(*state,
source == sInstalled ? installedElems : availElems,
opArgs, false);
@@ -1067,9 +1070,7 @@ static void opQuery(Globals & globals, Strings opFlags, Strings opArgs)
/* !!! */
std::vector<DrvInfo> elems;
for (auto & i : elems_) elems.push_back(i);
sort(elems.begin(), elems.end(), [&](auto & a, auto & b) {
return cmpElemByName(*globals.state, a, b);
});
sort(elems.begin(), elems.end(), [&] (auto& a, auto& b) { return cmpElemByName(*state, a, b); });
/* We only need to know the installed paths when we are querying
the status of the derivation. */
@@ -1077,7 +1078,7 @@ static void opQuery(Globals & globals, Strings opFlags, Strings opArgs)
if (printStatus)
for (auto & i : installedElems)
installed.insert(i.queryOutPath(*globals.state));
installed.insert(i.queryOutPath(*state));
/* Query which paths have substitutes. */
@@ -1087,13 +1088,9 @@ static void opQuery(Globals & globals, Strings opFlags, Strings opArgs)
StorePathSet paths;
for (auto & i : elems)
try {
paths.insert(i.queryOutPath(*globals.state));
paths.insert(i.queryOutPath(*state));
} catch (AssertionError & e) {
printMsg(
lvlTalkative,
"skipping derivation named '%s' which gives an assertion failure",
i.queryName(*globals.state)
);
printMsg(lvlTalkative, "skipping derivation named '%s' which gives an assertion failure", i.queryName(*state));
i.setFailed();
}
validPaths = store.queryValidPaths(paths);
@@ -1103,7 +1100,7 @@ static void opQuery(Globals & globals, Strings opFlags, Strings opArgs)
/* Print the desired columns, or XML output. */
if (jsonOutput) {
queryJSON(globals, elems, printOutPath, printDrvPath, printMeta);
queryJSON(*state, globals, elems, printOutPath, printDrvPath, printMeta);
cout << '\n';
return;
}
@@ -1122,8 +1119,8 @@ static void opQuery(Globals & globals, Strings opFlags, Strings opArgs)
//Activity act(*logger, lvlDebug, "outputting query result '%1%'", i.attrPath);
if (globals.prebuiltOnly &&
!validPaths.count(i.queryOutPath(*globals.state)) &&
!substitutablePaths.count(i.queryOutPath(*globals.state)))
!validPaths.count(i.queryOutPath(*state)) &&
!substitutablePaths.count(i.queryOutPath(*state)))
continue;
/* For table output. */
@@ -1133,7 +1130,7 @@ static void opQuery(Globals & globals, Strings opFlags, Strings opArgs)
XMLAttrs attrs;
if (printStatus) {
auto outPath = i.queryOutPath(*globals.state);
auto outPath = i.queryOutPath(*state);
bool hasSubs = substitutablePaths.count(outPath);
bool isInstalled = installed.count(outPath);
bool isValid = validPaths.count(outPath);
@@ -1154,12 +1151,12 @@ static void opQuery(Globals & globals, Strings opFlags, Strings opArgs)
columns.push_back(i.attrPath);
if (xmlOutput) {
auto drvName = DrvName(i.queryName(*globals.state));
auto drvName = DrvName(i.queryName(*state));
attrs["name"] = drvName.fullName;
attrs["pname"] = drvName.name;
attrs["version"] = drvName.version;
} else if (printName) {
columns.push_back(i.queryName(*globals.state));
columns.push_back(i.queryName(*state));
}
if (compareVersions) {
@@ -1168,7 +1165,7 @@ static void opQuery(Globals & globals, Strings opFlags, Strings opArgs)
elements, or the set of installed elements. !!!
This is O(N * M), should be O(N * lg M). */
std::string version;
VersionDiff diff = compareVersionAgainstSet(*globals.state, i, otherElems, version);
VersionDiff diff = compareVersionAgainstSet(*state, i, otherElems, version);
char ch;
switch (diff) {
@@ -1193,13 +1190,13 @@ static void opQuery(Globals & globals, Strings opFlags, Strings opArgs)
}
if (xmlOutput) {
if (i.querySystem(*globals.state) != "") attrs["system"] = i.querySystem(*globals.state);
if (i.querySystem(*state) != "") attrs["system"] = i.querySystem(*state);
}
else if (printSystem)
columns.push_back(i.querySystem(*globals.state));
columns.push_back(i.querySystem(*state));
if (printDrvPath) {
auto drvPath = i.queryDrvPath(*globals.state);
auto drvPath = i.queryDrvPath(*state);
if (xmlOutput) {
if (drvPath) attrs["drvPath"] = store.printStorePath(*drvPath);
} else
@@ -1207,10 +1204,10 @@ static void opQuery(Globals & globals, Strings opFlags, Strings opArgs)
}
if (xmlOutput)
attrs["outputName"] = i.queryOutputName(*globals.state);
attrs["outputName"] = i.queryOutputName(*state);
if (printOutPath && !xmlOutput) {
DrvInfo::Outputs outputs = i.queryOutputs(*globals.state);
DrvInfo::Outputs outputs = i.queryOutputs(*state);
std::string s;
for (auto & j : outputs) {
if (!s.empty()) s += ';';
@@ -1221,7 +1218,7 @@ static void opQuery(Globals & globals, Strings opFlags, Strings opArgs)
}
if (printDescription) {
auto descr = i.queryMetaString(*globals.state, "description");
auto descr = i.queryMetaString(*state, "description");
if (xmlOutput) {
if (descr != "") attrs["description"] = descr;
} else
@@ -1230,7 +1227,7 @@ static void opQuery(Globals & globals, Strings opFlags, Strings opArgs)
if (xmlOutput) {
XMLOpenElement item(xml, "item", attrs);
DrvInfo::Outputs outputs = i.queryOutputs(*globals.state, printOutPath);
DrvInfo::Outputs outputs = i.queryOutputs(*state, printOutPath);
for (auto & j : outputs) {
XMLAttrs attrs2;
attrs2["name"] = j.first;
@@ -1239,15 +1236,15 @@ static void opQuery(Globals & globals, Strings opFlags, Strings opArgs)
xml.writeEmptyElement("output", attrs2);
}
if (printMeta) {
StringSet metaNames = i.queryMetaNames(*globals.state);
StringSet metaNames = i.queryMetaNames(*state);
for (auto & j : metaNames) {
XMLAttrs attrs2;
attrs2["name"] = j;
Value * v = i.queryMeta(*globals.state, j);
Value * v = i.queryMeta(*state, j);
if (!v)
printError(
"derivation '%s' has invalid meta attribute '%s'",
i.queryName(*globals.state), j);
i.queryName(*state), j);
else {
if (v->type() == nString) {
attrs2["type"] = "string";
@@ -1296,13 +1293,9 @@ static void opQuery(Globals & globals, Strings opFlags, Strings opArgs)
cout.flush();
} catch (AssertionError & e) {
printMsg(
lvlTalkative,
"skipping derivation named '%1%' which gives an assertion failure",
i.queryName(*globals.state)
);
printMsg(lvlTalkative, "skipping derivation named '%1%' which gives an assertion failure", i.queryName(*state));
} catch (Error & e) {
e.addTrace(nullptr, "while querying the derivation named '%1%'", i.queryName(*globals.state));
e.addTrace(nullptr, "while querying the derivation named '%1%'", i.queryName(*state));
throw;
}
}
+9 -8
View File
@@ -157,16 +157,17 @@ static int main_nix_instantiate(std::string programName, Strings argv)
auto store = openStore();
auto evalStore = myArgs.evalStoreUrl ? openStore(*myArgs.evalStoreUrl) : store;
auto state = std::make_unique<EvalState>(myArgs.searchPath, evalStore, store);
state->repair = myArgs.repair;
auto evaluator = std::make_unique<EvalState>(myArgs.searchPath, evalStore, store);
auto & state = evaluator;
evaluator->repair = myArgs.repair;
Bindings & autoArgs = *myArgs.getAutoArgs(*state);
Bindings & autoArgs = *myArgs.getAutoArgs(*evaluator);
if (attrPaths.empty()) attrPaths = {""};
if (findFile) {
for (auto & i : files) {
auto p = state->paths.findFile(i);
auto p = evaluator->paths.findFile(i);
if (auto fn = p.getPhysicalPath())
std::cout << fn->abs() << std::endl;
else
@@ -176,7 +177,7 @@ static int main_nix_instantiate(std::string programName, Strings argv)
}
if (readStdin) {
Expr & e = state->parseStdin();
Expr & e = evaluator->parseStdin();
processExpr(*state, attrPaths, parseOnly, strict, autoArgs,
evalOnly, outputKind, xmlOutputSourceLocation, e);
} else if (files.empty() && !fromArgs)
@@ -184,13 +185,13 @@ static int main_nix_instantiate(std::string programName, Strings argv)
for (auto & i : files) {
Expr & e = fromArgs
? state->parseExprFromString(i, CanonPath::fromCwd())
: state->parseExprFromFile(resolveExprPath(state->paths.checkSourcePath(lookupFileArg(*state, i))));
? evaluator->parseExprFromString(i, CanonPath::fromCwd())
: evaluator->parseExprFromFile(resolveExprPath(evaluator->paths.checkSourcePath(lookupFileArg(*evaluator, i))));
processExpr(*state, attrPaths, parseOnly, strict, autoArgs,
evalOnly, outputKind, xmlOutputSourceLocation, e);
}
state->maybePrintStats();
evaluator->maybePrintStats();
return 0;
}
+2 -2
View File
@@ -26,7 +26,7 @@ InstallableAttrPath::InstallableAttrPath(
std::pair<Value *, PosIdx> InstallableAttrPath::toValue()
{
auto [vRes, pos] = findAlongAttrPath(*state, attrPath, *cmd.getAutoArgs(*state), **v);
auto [vRes, pos] = findAlongAttrPath(*state, attrPath, *cmd.getAutoArgs(*evaluator), **v);
state->forceValue(*vRes, pos);
return {vRes, pos};
}
@@ -43,7 +43,7 @@ DerivedPathsWithInfo InstallableAttrPath::toDerivedPaths()
return { *derivedPathWithInfo };
}
Bindings & autoArgs = *cmd.getAutoArgs(*state);
Bindings & autoArgs = *cmd.getAutoArgs(*evaluator);
DrvInfos drvInfos;
getDerivations(*state, *v, "", autoArgs, drvInfos, false);
+1 -1
View File
@@ -158,7 +158,7 @@ std::pair<Value *, PosIdx> InstallableFlake::toValue()
std::vector<ref<eval_cache::AttrCursor>>
InstallableFlake::getCursors()
{
auto evalCache = openEvalCache(*state, getLockedFlake());
auto evalCache = openEvalCache(*evaluator, getLockedFlake());
auto root = evalCache->getRoot();
+6 -1
View File
@@ -70,9 +70,14 @@ struct ExtraPathInfoValue : ExtraPathInfo
*/
struct InstallableValue : Installable
{
ref<eval_cache::CachingEvalState> evaluator;
ref<eval_cache::CachingEvalState> state;
InstallableValue(ref<eval_cache::CachingEvalState> state) : state(state) {}
InstallableValue(ref<eval_cache::CachingEvalState> evaluator)
: evaluator(evaluator)
, state(evaluator)
{
}
virtual ~InstallableValue() { }
+72 -70
View File
@@ -119,6 +119,7 @@ struct NixRepl
};
/* clang-format: on */
EvalState & evaluator;
size_t debugTraceIndex;
Strings loadedFiles;
@@ -231,9 +232,10 @@ static box_ptr<ReplInteracter> makeInteracter() {
NixRepl::NixRepl(const SearchPath & searchPath, nix::ref<Store> store, EvalState & state,
std::function<NixRepl::AnnotatedValues()> getValues)
: AbstractNixRepl(state)
, evaluator(state)
, debugTraceIndex(0)
, getValues(getValues)
, staticEnv(new StaticEnv(nullptr, state.builtins.staticEnv.get()))
, staticEnv(new StaticEnv(nullptr, evaluator.builtins.staticEnv.get()))
, interacter(makeInteracter())
{
}
@@ -281,7 +283,7 @@ ReplExitStatus NixRepl::mainLoop()
{
if (isFirstRepl) {
std::string_view debuggerNotice = "";
if (state.debug && state.debug->inDebugger) {
if (evaluator.debug && evaluator.debug->inDebugger) {
debuggerNotice = " debugger";
}
notice("Lix %1%%2%\nType :? for help.", nixVersion, debuggerNotice);
@@ -306,8 +308,8 @@ ReplExitStatus NixRepl::mainLoop()
// number of chars as the prompt.
if (!interacter->getLine(input, input.empty() ? ReplPromptType::ReplPrompt : ReplPromptType::ContinuationPrompt)) {
// Ctrl-D should exit the debugger.
if (state.debug) {
state.debug->stop = false;
if (evaluator.debug) {
evaluator.debug->stop = false;
}
logger->cout("");
// TODO: Should Ctrl-D exit just the current debugger session or
@@ -364,7 +366,7 @@ StringSet NixRepl::completePrefix(const std::string & prefix)
}
}
if (state.debug && state.debug->inDebugger) {
if (evaluator.debug && evaluator.debug->inDebugger) {
for (auto const & colonCmd : this->DEBUG_COMMANDS) {
if (colonCmd.starts_with(prefix)) {
completions.insert(std::string(colonCmd));
@@ -414,8 +416,8 @@ StringSet NixRepl::completePrefix(const std::string & prefix)
}
} else {
/* Temporarily disable the debugger, to avoid re-entering readline. */
auto debug = std::move(state.debug);
Finally restoreDebug([&]() { state.debug = std::move(debug); });
auto debug = std::move(evaluator.debug);
Finally restoreDebug([&]() { evaluator.debug = std::move(debug); });
try {
/* This is an expression that should evaluate to an
attribute set. Evaluate it to get the names of the
@@ -429,7 +431,7 @@ StringSet NixRepl::completePrefix(const std::string & prefix)
state.forceAttrs(v, noPos, "while evaluating an attrset for the purpose of completion (this error should not be displayed; file an issue?)");
for (auto & i : *v.attrs) {
std::string_view name = state.symbols[i.name];
std::string_view name = evaluator.symbols[i.name];
if (name.substr(0, cur2.size()) != cur2) continue;
completions.insert(concatStrings(prev, expr, ".", name));
}
@@ -473,8 +475,8 @@ StorePath NixRepl::getDerivationPath(Value & v) {
auto drvPath = drvInfo->queryDrvPath(state);
if (!drvPath)
throw Error("expression did not evaluate to a valid derivation (no 'drvPath' attribute)");
if (!state.store->isValidPath(*drvPath))
throw Error("expression evaluated to invalid derivation '%s'", state.store->printStorePath(*drvPath));
if (!evaluator.store->isValidPath(*drvPath))
throw Error("expression evaluated to invalid derivation '%s'", evaluator.store->printStorePath(*drvPath));
return *drvPath;
}
@@ -482,13 +484,13 @@ void NixRepl::loadDebugTraceEnv(const DebugTrace & dt)
{
initEnv();
auto se = state.debug->staticEnvFor(dt.expr);
auto se = evaluator.debug->staticEnvFor(dt.expr);
if (se) {
auto vm = mapStaticEnvBindings(state.symbols, *se.get(), dt.env);
auto vm = mapStaticEnvBindings(evaluator.symbols, *se.get(), dt.env);
// add staticenv vars.
for (auto & [name, value] : *(vm.get()))
addVarToScope(state.symbols.create(name), *value);
addVarToScope(evaluator.symbols.create(name), *value);
}
}
@@ -538,7 +540,7 @@ ProcessLineResult NixRepl::processLine(std::string line)
<< " errors\n"
<< " :?, :help Brings up this help menu\n"
;
if (state.debug && state.debug->inDebugger) {
if (evaluator.debug && evaluator.debug->inDebugger) {
std::cout
<< "\n"
<< " Debug mode commands\n"
@@ -553,16 +555,16 @@ ProcessLineResult NixRepl::processLine(std::string line)
}
else if (state.debug && state.debug->inDebugger && (command == ":bt" || command == ":backtrace")) {
auto traces = state.debug->traces();
else if (evaluator.debug && evaluator.debug->inDebugger && (command == ":bt" || command == ":backtrace")) {
auto traces = evaluator.debug->traces();
for (const auto & [idx, i] : enumerate(traces)) {
std::cout << "\n" << ANSI_BLUE << idx << ANSI_NORMAL << ": ";
showDebugTrace(std::cout, state.positions, *i);
showDebugTrace(std::cout, evaluator.positions, *i);
}
}
else if (state.debug && state.debug->inDebugger && (command == ":env")) {
auto traces = state.debug->traces();
else if (evaluator.debug && evaluator.debug->inDebugger && (command == ":env")) {
auto traces = evaluator.debug->traces();
for (const auto & [idx, i] : enumerate(traces)) {
if (idx == debugTraceIndex) {
printEnvBindings(state, i->expr, i->env);
@@ -571,17 +573,17 @@ ProcessLineResult NixRepl::processLine(std::string line)
}
}
else if (state.debug && state.debug->inDebugger && (command == ":st")) {
else if (evaluator.debug && evaluator.debug->inDebugger && (command == ":st")) {
try {
// change the DebugTrace index.
debugTraceIndex = stoi(arg);
} catch (...) { }
auto traces = state.debug->traces();
auto traces = evaluator.debug->traces();
for (const auto & [idx, i] : enumerate(traces)) {
if (idx == debugTraceIndex) {
std::cout << "\n" << ANSI_BLUE << idx << ANSI_NORMAL << ": ";
showDebugTrace(std::cout, state.positions, *i);
showDebugTrace(std::cout, evaluator.positions, *i);
std::cout << std::endl;
printEnvBindings(state, i->expr, i->env);
loadDebugTraceEnv(*i);
@@ -590,15 +592,15 @@ ProcessLineResult NixRepl::processLine(std::string line)
}
}
else if (state.debug && state.debug->inDebugger && (command == ":s" || command == ":step")) {
else if (evaluator.debug && evaluator.debug->inDebugger && (command == ":s" || command == ":step")) {
// set flag to stop at next DebugTrace; exit repl.
state.debug->stop = true;
evaluator.debug->stop = true;
return ProcessLineResult::Continue;
}
else if (state.debug && state.debug->inDebugger && (command == ":c" || command == ":continue")) {
else if (evaluator.debug && evaluator.debug->inDebugger && (command == ":c" || command == ":continue")) {
// set flag to run to next breakpoint or end of program; exit repl.
state.debug->stop = false;
evaluator.debug->stop = false;
return ProcessLineResult::Continue;
}
@@ -632,7 +634,7 @@ ProcessLineResult NixRepl::processLine(std::string line)
auto path = state.coerceToPath(noPos, v, context, "while evaluating the filename to edit");
return {path, 0};
} else if (v.isLambda()) {
auto pos = state.positions[v.lambda.fun->pos];
auto pos = evaluator.positions[v.lambda.fun->pos];
if (auto path = std::get_if<SourcePath>(&pos.origin))
return {*path, pos.line};
else
@@ -654,7 +656,7 @@ ProcessLineResult NixRepl::processLine(std::string line)
// Reload right after exiting the editor if path is not in store
// Store is immutable, so there could be no changes, so there's no need to reload
if (!state.store->isInStore(path.resolveSymlinks().path.abs())) {
if (!evaluator.store->isInStore(path.resolveSymlinks().path.abs())) {
state.resetFileCache();
reloadFiles();
}
@@ -673,12 +675,12 @@ ProcessLineResult NixRepl::processLine(std::string line)
state.callFunction(f, v, result, PosIdx());
StorePath drvPath = getDerivationPath(result);
runNix("nix-shell", {state.store->printStorePath(drvPath)});
runNix("nix-shell", {evaluator.store->printStorePath(drvPath)});
}
else if (command == ":log") {
StorePath drvPath = ([&] {
auto maybeDrvPath = state.store->maybeParseStorePath(arg);
auto maybeDrvPath = evaluator.store->maybeParseStorePath(arg);
if (maybeDrvPath && maybeDrvPath->isDerivation()) {
return std::move(*maybeDrvPath);
} else {
@@ -687,7 +689,7 @@ ProcessLineResult NixRepl::processLine(std::string line)
return getDerivationPath(v);
}
})();
Path drvPathRaw = state.store->printStorePath(drvPath);
Path drvPathRaw = evaluator.store->printStorePath(drvPath);
settings.readOnlyMode = true;
Finally roModeReset([&]() {
@@ -695,7 +697,7 @@ ProcessLineResult NixRepl::processLine(std::string line)
});
auto subs = getDefaultSubstituters();
subs.push_front(state.store);
subs.push_front(evaluator.store);
bool foundLog = false;
RunPager pager;
@@ -722,7 +724,7 @@ ProcessLineResult NixRepl::processLine(std::string line)
Value v;
evalString(arg, v);
StorePath drvPath = getDerivationPath(v);
Path drvPathRaw = state.store->printStorePath(drvPath);
Path drvPathRaw = evaluator.store->printStorePath(drvPath);
if (command == ":b" || command == ":bl") {
// TODO: this only shows a progress bar for explicitly initiated builds,
@@ -734,22 +736,22 @@ ProcessLineResult NixRepl::processLine(std::string line)
logger->pause();
});
state.store->buildPaths({
evaluator.store->buildPaths({
DerivedPath::Built {
.drvPath = makeConstantStorePathRef(drvPath),
.outputs = OutputsSpec::All { },
},
});
auto drv = state.store->readDerivation(drvPath);
auto drv = evaluator.store->readDerivation(drvPath);
logger->cout("\nThis derivation produced the following outputs:");
for (auto & [outputName, outputPath] : state.store->queryDerivationOutputMap(drvPath)) {
auto localStore = state.store.dynamic_pointer_cast<LocalFSStore>();
for (auto & [outputName, outputPath] : evaluator.store->queryDerivationOutputMap(drvPath)) {
auto localStore = evaluator.store.dynamic_pointer_cast<LocalFSStore>();
if (localStore && command == ":bl") {
std::string symlink = "repl-result-" + outputName;
localStore->addPermRoot(outputPath, absPath(symlink));
logger->cout(" ./%s -> %s", symlink, state.store->printStorePath(outputPath));
logger->cout(" ./%s -> %s", symlink, evaluator.store->printStorePath(outputPath));
} else {
logger->cout(" %s -> %s", outputName, state.store->printStorePath(outputPath));
logger->cout(" %s -> %s", outputName, evaluator.store->printStorePath(outputPath));
}
}
} else if (command == ":i") {
@@ -771,8 +773,8 @@ ProcessLineResult NixRepl::processLine(std::string line)
}
else if (command == ":q" || command == ":quit") {
if (state.debug) {
state.debug->stop = false;
if (evaluator.debug) {
evaluator.debug->stop = false;
}
return ProcessLineResult::Quit;
}
@@ -780,7 +782,7 @@ ProcessLineResult NixRepl::processLine(std::string line)
else if (command == ":doc") {
Value v;
evalString(arg, v);
if (auto doc = state.builtins.getDoc(v)) {
if (auto doc = evaluator.builtins.getDoc(v)) {
std::string markdown;
if (!doc->args.empty() && doc->name) {
@@ -797,7 +799,7 @@ ProcessLineResult NixRepl::processLine(std::string line)
logger->cout(trim(renderMarkdownToTerminal(markdown)));
} else if (v.isLambda()) {
auto pos = state.positions[v.lambda.fun->pos];
auto pos = evaluator.positions[v.lambda.fun->pos];
if (auto path = std::get_if<SourcePath>(&pos.origin)) {
// Path and position have now been obtained, feed to nix-doc library to get data.
auto docComment = lambdaDocsForPos(*path, pos);
@@ -840,9 +842,9 @@ ProcessLineResult NixRepl::processLine(std::string line)
isVarName(name = removeWhitespace(line.substr(0, p))))
{
Expr & e = parseString(line.substr(p + 1));
Value & v(*state.mem.allocValue());
Value & v(*evaluator.mem.allocValue());
v.mkThunk(env, e);
addVarToScope(state.symbols.create(name), v);
addVarToScope(evaluator.symbols.create(name), v);
} else {
Value v;
evalString(line, v);
@@ -859,7 +861,7 @@ void NixRepl::loadFile(const Path & path)
loadedFiles.remove(path);
loadedFiles.push_back(path);
Value v, v2;
state.evalFile(lookupFileArg(state, path), v);
state.evalFile(lookupFileArg(evaluator, path), v);
state.autoCallFunction(*autoArgs, v, v2);
addAttrsToScope(v2);
}
@@ -889,14 +891,14 @@ void NixRepl::loadFlake(const std::string & flakeRefS)
void NixRepl::initEnv()
{
env = &state.mem.allocEnv(envSize);
env->up = &state.builtins.env;
env = &evaluator.mem.allocEnv(envSize);
env->up = &evaluator.builtins.env;
displ = 0;
staticEnv->vars.clear();
varNames.clear();
for (auto & i : state.builtins.staticEnv->vars)
varNames.emplace(state.symbols[i.first]);
for (auto & i : evaluator.builtins.staticEnv->vars)
varNames.emplace(evaluator.symbols[i.first]);
}
@@ -935,7 +937,7 @@ void NixRepl::loadReplOverlays()
notice("Loading '%1%'...", Magenta("repl-overlays"));
auto replInitFilesFunction = getReplOverlaysEvalFunction();
Value &newAttrs(*state.mem.allocValue());
Value &newAttrs(*evaluator.mem.allocValue());
SmallValueVector<3> args = {replInitInfo(), bindingsToAttrs(), replOverlays()};
state.callFunction(
*replInitFilesFunction,
@@ -960,14 +962,14 @@ Value * NixRepl::getReplOverlaysEvalFunction()
}
auto evalReplInitFilesPath = CanonPath::root + "repl-overlays.nix";
*replOverlaysEvalFunction = state.mem.allocValue();
*replOverlaysEvalFunction = evaluator.mem.allocValue();
auto code =
#include "repl-overlays.nix.gen.hh"
;
auto & expr = state.parseExprFromString(
auto & expr = evaluator.parseExprFromString(
code,
SourcePath(evalReplInitFilesPath),
state.builtins.staticEnv
evaluator.builtins.staticEnv
);
state.eval(expr, **replOverlaysEvalFunction);
@@ -977,8 +979,8 @@ Value * NixRepl::getReplOverlaysEvalFunction()
Value * NixRepl::replOverlays()
{
Value * replInits(state.mem.allocValue());
*replInits = state.mem.newList(evalSettings.replOverlays.get().size());
Value * replInits(evaluator.mem.allocValue());
*replInits = evaluator.mem.newList(evalSettings.replOverlays.get().size());
Value ** replInitElems = replInits->listElems();
size_t i = 0;
@@ -988,7 +990,7 @@ Value * NixRepl::replOverlays()
auto replInit = evalFile(sourcePath);
if (!replInit->isLambda()) {
state.errors.make<TypeError>(
evaluator.errors.make<TypeError>(
"Expected `repl-overlays` to be a lambda but found %1%: %2%",
showType(*replInit),
ValuePrinter(state, *replInit, errorPrintOptions)
@@ -999,7 +1001,7 @@ Value * NixRepl::replOverlays()
if (replInit->lambda.fun->hasFormals()
&& !replInit->lambda.fun->formals->ellipsis) {
state.errors.make<TypeError>(
evaluator.errors.make<TypeError>(
"Expected first argument of %1% to have %2% to allow future versions of Lix to add additional attributes to the argument",
"repl-overlays",
"..."
@@ -1018,13 +1020,13 @@ Value * NixRepl::replOverlays()
Value * NixRepl::replInitInfo()
{
auto builder = state.buildBindings(2);
auto builder = evaluator.buildBindings(2);
Value * currentSystem(state.mem.allocValue());
Value * currentSystem(evaluator.mem.allocValue());
currentSystem->mkString(evalSettings.getCurrentSystem());
builder.insert(state.symbols.create("currentSystem"), currentSystem);
builder.insert(evaluator.symbols.create("currentSystem"), currentSystem);
Value * info(state.mem.allocValue());
Value * info(evaluator.mem.allocValue());
info->mkAttrs(builder.finish());
return info;
}
@@ -1039,7 +1041,7 @@ void NixRepl::addAttrsToScope(Value & attrs)
for (auto & i : *attrs.attrs) {
staticEnv->vars.emplace_back(i.name, displ);
env->values[displ++] = i.value;
varNames.emplace(state.symbols[i.name]);
varNames.emplace(evaluator.symbols[i.name]);
}
staticEnv->sort();
staticEnv->deduplicate();
@@ -1056,17 +1058,17 @@ void NixRepl::addVarToScope(const Symbol name, Value & v)
staticEnv->vars.emplace_back(name, displ);
staticEnv->sort();
env->values[displ++] = &v;
varNames.emplace(state.symbols[name]);
varNames.emplace(evaluator.symbols[name]);
}
Value * NixRepl::bindingsToAttrs()
{
auto builder = state.buildBindings(staticEnv->vars.size());
auto builder = evaluator.buildBindings(staticEnv->vars.size());
for (auto & [symbol, displacement] : staticEnv->vars) {
builder.insert(symbol, env->values[displacement]);
}
Value * attrs(state.mem.allocValue());
Value * attrs(evaluator.mem.allocValue());
attrs->mkAttrs(builder.finish());
return attrs;
}
@@ -1074,7 +1076,7 @@ Value * NixRepl::bindingsToAttrs()
Expr & NixRepl::parseString(std::string s)
{
return state.parseExprFromString(std::move(s), CanonPath::fromCwd(), staticEnv);
return evaluator.parseExprFromString(std::move(s), CanonPath::fromCwd(), staticEnv);
}
@@ -1087,8 +1089,8 @@ void NixRepl::evalString(std::string s, Value & v)
Value * NixRepl::evalFile(SourcePath & path)
{
auto & expr = state.parseExprFromFile(path, staticEnv);
Value * result(state.mem.allocValue());
auto & expr = evaluator.parseExprFromFile(path, staticEnv);
Value * result(evaluator.mem.allocValue());
expr.eval(state, *env, *result);
state.forceValue(*result, result->determinePos(noPos));
return result;
@@ -1108,7 +1110,7 @@ ReplExitStatus AbstractNixRepl::run(
repl.autoArgs = autoArgs;
repl.initEnv();
for (auto & [name, value] : extraEnv) {
repl.addVarToScope(repl.state.symbols.create(name), *value);
repl.addVarToScope(repl.evaluator.symbols.create(name), *value);
}
return repl.mainLoop();
}
+7 -6
View File
@@ -73,7 +73,8 @@ struct CmdBundle : InstallableCommand
void run(ref<Store> store, ref<Installable> installable) override
{
auto evalState = getEvalState();
auto evaluator = getEvalState();
auto evalState = evaluator;
auto const installableValue = InstallableValue::require(installable);
@@ -82,7 +83,7 @@ struct CmdBundle : InstallableCommand
auto [bundlerFlakeRef, bundlerName, extendedOutputsSpec] = parseFlakeRefWithFragmentAndExtendedOutputsSpec(bundler, absPath("."));
const flake::LockFlags lockFlags{ .writeLockFile = false };
InstallableFlake bundler{this,
evalState, std::move(bundlerFlakeRef), bundlerName, std::move(extendedOutputsSpec),
evaluator, std::move(bundlerFlakeRef), bundlerName, std::move(extendedOutputsSpec),
{"bundlers." + settings.thisSystem.get() + ".default",
"defaultBundler." + settings.thisSystem.get()
},
@@ -90,20 +91,20 @@ struct CmdBundle : InstallableCommand
lockFlags
};
auto vRes = evalState->mem.allocValue();
auto vRes = evaluator->mem.allocValue();
evalState->callFunction(*bundler.toValue().first, *val, *vRes, noPos);
if (!evalState->isDerivation(*vRes))
throw Error("the bundler '%s' does not produce a derivation", bundler.what());
auto attr1 = vRes->attrs->get(evalState->s.drvPath);
auto attr1 = vRes->attrs->get(evaluator->s.drvPath);
if (!attr1)
throw Error("the bundler '%s' does not produce a derivation", bundler.what());
NixStringContext context2;
auto drvPath = evalState->coerceToStorePath(attr1->pos, *attr1->value, context2, "");
auto attr2 = vRes->attrs->get(evalState->s.outPath);
auto attr2 = vRes->attrs->get(evaluator->s.outPath);
if (!attr2)
throw Error("the bundler '%s' does not produce a derivation", bundler.what());
@@ -119,7 +120,7 @@ struct CmdBundle : InstallableCommand
auto outPathS = store->printStorePath(outPath);
if (!outLink) {
auto * attr = vRes->attrs->get(evalState->s.name);
auto * attr = vRes->attrs->get(evaluator->s.name);
if (!attr)
throw Error("attribute 'name' missing");
outLink = evalState->forceStringNoCtx(*attr->value, attr->pos, "");
+3 -2
View File
@@ -547,6 +547,9 @@ struct CmdDevelop : Common, MixEnvironment
void run(ref<Store> store, ref<Installable> installable) override
{
auto evaluator = getEvalState();
auto state = evaluator;
auto [buildEnvironment, gcroot] = getBuildEnvironment(store, installable);
auto [rcFileFd, rcFilePath] = createTempFile("nix-shell");
@@ -598,8 +601,6 @@ struct CmdDevelop : Common, MixEnvironment
Path shell = "bash";
try {
auto state = getEvalState();
auto nixpkgsLockFlags = lockFlags;
nixpkgsLockFlags.inputOverrides = {};
nixpkgsLockFlags.inputUpdates = {};
+2 -1
View File
@@ -27,7 +27,8 @@ struct CmdEdit : InstallableCommand
void run(ref<Store> store, ref<Installable> installable) override
{
auto state = getEvalState();
auto evaluator = getEvalState();
auto state = evaluator;
auto const installableValue = InstallableValue::require(installable);
+8 -7
View File
@@ -61,15 +61,16 @@ struct CmdEval : MixJSON, InstallableCommand, MixReadOnlyOption
auto const installableValue = InstallableValue::require(installable);
auto state = getEvalState();
auto evaluator = getEvalState();
auto state = evaluator;
auto [v, pos] = installableValue->toValue();
NixStringContext context;
if (apply) {
auto vApply = state->mem.allocValue();
state->eval(state->parseExprFromString(*apply, CanonPath::fromCwd()), *vApply);
auto vRes = state->mem.allocValue();
auto vApply = evaluator->mem.allocValue();
state->eval(evaluator->parseExprFromString(*apply, CanonPath::fromCwd()), *vApply);
auto vRes = evaluator->mem.allocValue();
state->callFunction(*vApply, *v, *vRes, noPos);
v = vRes;
}
@@ -92,21 +93,21 @@ struct CmdEval : MixJSON, InstallableCommand, MixReadOnlyOption
if (mkdir(path.c_str(), 0777) == -1)
throw SysError("creating directory '%s'", path);
for (auto & attr : *v.attrs) {
std::string_view name = state->symbols[attr.name];
std::string_view name = evaluator->symbols[attr.name];
try {
if (name == "." || name == "..")
throw Error("invalid file name '%s'", name);
recurse(*attr.value, attr.pos, concatStrings(path, "/", name));
} catch (Error & e) {
e.addTrace(
state->positions[attr.pos],
evaluator->positions[attr.pos],
HintFmt("while evaluating the attribute '%s'", name));
throw;
}
}
}
else
state->errors.make<TypeError>("value at '%s' is not a string or an attribute set", state->positions[pos]).debugThrow();
evaluator->errors.make<TypeError>("value at '%s' is not a string or an attribute set", evaluator->positions[pos]).debugThrow();
};
recurse(*v, pos, *writeTo);
+37 -34
View File
@@ -358,7 +358,8 @@ struct CmdFlakeCheck : FlakeCommand
evalSettings.enableImportFromDerivation.setDefault(false);
}
auto state = getEvalState();
auto evaluator = getEvalState();
auto state = evaluator;
lockFlags.applyNixConfig = true;
auto flake = lockFlake();
@@ -385,11 +386,11 @@ struct CmdFlakeCheck : FlakeCommand
// FIXME: rewrite to use EvalCache.
auto resolve = [&] (PosIdx p) {
return state->positions[p];
return evaluator->positions[p];
};
auto argHasName = [&] (Symbol arg, std::string_view expected) {
std::string_view name = state->symbols[arg];
std::string_view name = evaluator->symbols[arg];
return
name == expected
|| name == "_"
@@ -501,7 +502,7 @@ struct CmdFlakeCheck : FlakeCommand
for (auto & attr : *v.attrs) {
state->forceAttrs(*attr.value, attr.pos, "");
auto attrPath2 = concatStrings(attrPath, ".", state->symbols[attr.name]);
auto attrPath2 = concatStrings(attrPath, ".", evaluator->symbols[attr.name]);
if (state->isDerivation(*attr.value)) {
Activity act(*logger, lvlInfo, actUnknown,
fmt("checking Hydra job '%s'", attrPath2));
@@ -520,7 +521,7 @@ struct CmdFlakeCheck : FlakeCommand
try {
Activity act(*logger, lvlInfo, actUnknown,
fmt("checking NixOS configuration '%s'", attrPath));
Bindings & bindings(*state->mem.allocBindings(0));
Bindings & bindings(*evaluator->mem.allocBindings(0));
auto vToplevel = findAlongAttrPath(*state, "config.system.build.toplevel", bindings, v).first;
state->forceValue(*vToplevel, pos);
if (!state->isDerivation(*vToplevel))
@@ -538,8 +539,8 @@ struct CmdFlakeCheck : FlakeCommand
state->forceAttrs(v, pos, "");
if (auto attr = v.attrs->get(state->symbols.create("path"))) {
if (attr->name == state->symbols.create("path")) {
if (auto attr = v.attrs->get(evaluator->symbols.create("path"))) {
if (attr->name == evaluator->symbols.create("path")) {
NixStringContext context;
auto path = state->coerceToPath(attr->pos, *attr->value, context, "");
if (!path.pathExists())
@@ -549,13 +550,13 @@ struct CmdFlakeCheck : FlakeCommand
} else
throw Error("template '%s' lacks attribute 'path'", attrPath);
if (auto attr = v.attrs->get(state->symbols.create("description")))
if (auto attr = v.attrs->get(evaluator->symbols.create("description")))
state->forceStringNoCtx(*attr->value, attr->pos, "");
else
throw Error("template '%s' lacks attribute 'description'", attrPath);
for (auto & attr : *v.attrs) {
std::string_view name(state->symbols[attr.name]);
std::string_view name(evaluator->symbols[attr.name]);
if (name != "path" && name != "description" && name != "welcomeText")
throw Error("template '%s' has unsupported attribute '%s'", attrPath, name);
}
@@ -582,7 +583,7 @@ struct CmdFlakeCheck : FlakeCommand
{
Activity act(*logger, lvlInfo, actUnknown, "evaluating flake");
auto vFlake = state->mem.allocValue();
auto vFlake = evaluator->mem.allocValue();
flake::callFlake(*state, flake, *vFlake);
enumerateOutputs(*state,
@@ -611,13 +612,13 @@ struct CmdFlakeCheck : FlakeCommand
if (name == "checks") {
state->forceAttrs(vOutput, pos, "");
for (auto & attr : *vOutput.attrs) {
const auto & attr_name = state->symbols[attr.name];
const auto & attr_name = evaluator->symbols[attr.name];
checkSystemName(attr_name, attr.pos);
if (checkSystemType(attr_name, attr.pos)) {
state->forceAttrs(*attr.value, attr.pos, "");
for (auto & attr2 : *attr.value->attrs) {
auto drvPath = checkDerivation(
fmt("%s.%s.%s", name, attr_name, state->symbols[attr2.name]),
fmt("%s.%s.%s", name, attr_name, evaluator->symbols[attr2.name]),
*attr2.value, attr2.pos);
if (drvPath && attr_name == settings.thisSystem.get()) {
drvPaths.push_back(DerivedPath::Built {
@@ -633,7 +634,7 @@ struct CmdFlakeCheck : FlakeCommand
else if (name == "formatter") {
state->forceAttrs(vOutput, pos, "");
for (auto & attr : *vOutput.attrs) {
const auto & attr_name = state->symbols[attr.name];
const auto & attr_name = evaluator->symbols[attr.name];
checkSystemName(attr_name, attr.pos);
if (checkSystemType(attr_name, attr.pos)) {
checkApp(
@@ -646,13 +647,13 @@ struct CmdFlakeCheck : FlakeCommand
else if (name == "packages" || name == "devShells") {
state->forceAttrs(vOutput, pos, "");
for (auto & attr : *vOutput.attrs) {
const auto & attr_name = state->symbols[attr.name];
const auto & attr_name = evaluator->symbols[attr.name];
checkSystemName(attr_name, attr.pos);
if (checkSystemType(attr_name, attr.pos)) {
state->forceAttrs(*attr.value, attr.pos, "");
for (auto & attr2 : *attr.value->attrs)
checkDerivation(
fmt("%s.%s.%s", name, attr_name, state->symbols[attr2.name]),
fmt("%s.%s.%s", name, attr_name, evaluator->symbols[attr2.name]),
*attr2.value, attr2.pos);
};
}
@@ -661,13 +662,13 @@ struct CmdFlakeCheck : FlakeCommand
else if (name == "apps") {
state->forceAttrs(vOutput, pos, "");
for (auto & attr : *vOutput.attrs) {
const auto & attr_name = state->symbols[attr.name];
const auto & attr_name = evaluator->symbols[attr.name];
checkSystemName(attr_name, attr.pos);
if (checkSystemType(attr_name, attr.pos)) {
state->forceAttrs(*attr.value, attr.pos, "");
for (auto & attr2 : *attr.value->attrs)
checkApp(
fmt("%s.%s.%s", name, attr_name, state->symbols[attr2.name]),
fmt("%s.%s.%s", name, attr_name, evaluator->symbols[attr2.name]),
*attr2.value, attr2.pos);
};
}
@@ -676,7 +677,7 @@ struct CmdFlakeCheck : FlakeCommand
else if (name == "defaultPackage" || name == "devShell") {
state->forceAttrs(vOutput, pos, "");
for (auto & attr : *vOutput.attrs) {
const auto & attr_name = state->symbols[attr.name];
const auto & attr_name = evaluator->symbols[attr.name];
checkSystemName(attr_name, attr.pos);
if (checkSystemType(attr_name, attr.pos)) {
checkDerivation(
@@ -689,7 +690,7 @@ struct CmdFlakeCheck : FlakeCommand
else if (name == "defaultApp") {
state->forceAttrs(vOutput, pos, "");
for (auto & attr : *vOutput.attrs) {
const auto & attr_name = state->symbols[attr.name];
const auto & attr_name = evaluator->symbols[attr.name];
checkSystemName(attr_name, attr.pos);
if (checkSystemType(attr_name, attr.pos) ) {
checkApp(
@@ -702,8 +703,8 @@ struct CmdFlakeCheck : FlakeCommand
else if (name == "legacyPackages") {
state->forceAttrs(vOutput, pos, "");
for (auto & attr : *vOutput.attrs) {
checkSystemName(state->symbols[attr.name], attr.pos);
checkSystemType(state->symbols[attr.name], attr.pos);
checkSystemName(evaluator->symbols[attr.name], attr.pos);
checkSystemType(evaluator->symbols[attr.name], attr.pos);
// FIXME: do getDerivations?
}
}
@@ -714,7 +715,7 @@ struct CmdFlakeCheck : FlakeCommand
else if (name == "overlays") {
state->forceAttrs(vOutput, pos, "");
for (auto & attr : *vOutput.attrs)
checkOverlay(fmt("%s.%s", name, state->symbols[attr.name]),
checkOverlay(fmt("%s.%s", name, evaluator->symbols[attr.name]),
*attr.value, attr.pos);
}
@@ -724,14 +725,14 @@ struct CmdFlakeCheck : FlakeCommand
else if (name == "nixosModules") {
state->forceAttrs(vOutput, pos, "");
for (auto & attr : *vOutput.attrs)
checkModule(fmt("%s.%s", name, state->symbols[attr.name]),
checkModule(fmt("%s.%s", name, evaluator->symbols[attr.name]),
*attr.value, attr.pos);
}
else if (name == "nixosConfigurations") {
state->forceAttrs(vOutput, pos, "");
for (auto & attr : *vOutput.attrs)
checkNixOSConfiguration(fmt("%s.%s", name, state->symbols[attr.name]),
checkNixOSConfiguration(fmt("%s.%s", name, evaluator->symbols[attr.name]),
*attr.value, attr.pos);
}
@@ -744,14 +745,14 @@ struct CmdFlakeCheck : FlakeCommand
else if (name == "templates") {
state->forceAttrs(vOutput, pos, "");
for (auto & attr : *vOutput.attrs)
checkTemplate(fmt("%s.%s", name, state->symbols[attr.name]),
checkTemplate(fmt("%s.%s", name, evaluator->symbols[attr.name]),
*attr.value, attr.pos);
}
else if (name == "defaultBundler") {
state->forceAttrs(vOutput, pos, "");
for (auto & attr : *vOutput.attrs) {
const auto & attr_name = state->symbols[attr.name];
const auto & attr_name = evaluator->symbols[attr.name];
checkSystemName(attr_name, attr.pos);
if (checkSystemType(attr_name, attr.pos)) {
checkBundler(
@@ -764,13 +765,13 @@ struct CmdFlakeCheck : FlakeCommand
else if (name == "bundlers") {
state->forceAttrs(vOutput, pos, "");
for (auto & attr : *vOutput.attrs) {
const auto & attr_name = state->symbols[attr.name];
const auto & attr_name = evaluator->symbols[attr.name];
checkSystemName(attr_name, attr.pos);
if (checkSystemType(attr_name, attr.pos)) {
state->forceAttrs(*attr.value, attr.pos, "");
for (auto & attr2 : *attr.value->attrs) {
checkBundler(
fmt("%s.%s.%s", name, attr_name, state->symbols[attr2.name]),
fmt("%s.%s.%s", name, attr_name, evaluator->symbols[attr2.name]),
*attr2.value, attr2.pos);
}
};
@@ -852,12 +853,13 @@ struct CmdFlakeInitCommon : virtual Args, EvalCommand
{
auto flakeDir = absPath(destDir);
auto evalState = getEvalState();
auto evaluator = getEvalState();
auto evalState = evaluator;
auto [templateFlakeRef, templateName] = parseFlakeRefWithFragment(templateUrl, absPath("."));
auto installable = InstallableFlake(nullptr,
evalState, std::move(templateFlakeRef), templateName, ExtendedOutputsSpec::Default(),
evaluator, std::move(templateFlakeRef), templateName, ExtendedOutputsSpec::Default(),
defaultTemplateAttrPaths,
defaultTemplateAttrPathsPrefixes,
lockFlags);
@@ -868,7 +870,7 @@ struct CmdFlakeInitCommon : virtual Args, EvalCommand
auto templateDir = templateDirAttr->getString(*evalState);
if (!store->isInStore(templateDir))
evalState->errors.make<TypeError>(
evaluator->errors.make<TypeError>(
"'%s' was not found in the Nix store\n"
"If you've set '%s' to a string, try using a path instead.",
templateDir, templateDirAttr->getAttrPathStr(*evalState)).debugThrow();
@@ -1130,7 +1132,8 @@ struct CmdFlakeShow : FlakeCommand, MixJSON
{
evalSettings.enableImportFromDerivation.setDefault(false);
auto state = getEvalState();
auto evaluator = getEvalState();
auto state = evaluator;
auto flake = std::make_shared<LockedFlake>(lockFlake());
auto localSystem = std::string(settings.thisSystem.get());
@@ -1368,7 +1371,7 @@ struct CmdFlakeShow : FlakeCommand, MixJSON
{
auto aType = visitor.maybeGetAttr(*state, "type");
if (!aType || aType->getString(*state) != "app")
state->errors.make<EvalError>("not an app definition").debugThrow();
evaluator->errors.make<EvalError>("not an app definition").debugThrow();
if (json) {
j.emplace("type", "app");
} else {
@@ -1411,7 +1414,7 @@ struct CmdFlakeShow : FlakeCommand, MixJSON
return j;
};
auto cache = openEvalCache(*state, flake);
auto cache = openEvalCache(*evaluator, flake);
auto j = visit(*cache->getRoot(), {}, fmt(ANSI_BOLD "%s" ANSI_NORMAL, flake->flake.lockedRef), "");
if (json)
+10 -9
View File
@@ -254,25 +254,26 @@ static void showHelp(std::vector<std::string> subcommand, NixArgs & toplevel)
evalSettings.restrictEval.override(false);
evalSettings.pureEval.override(false);
EvalState state({}, openStore("dummy://"));
EvalState evaluator({}, openStore("dummy://"));
auto * state = &evaluator;
auto vGenerateManpage = state.mem.allocValue();
state.eval(state.parseExprFromString(
auto vGenerateManpage = evaluator.mem.allocValue();
state->eval(evaluator.parseExprFromString(
#include "generate-manpage.nix.gen.hh"
, CanonPath::root), *vGenerateManpage);
auto vDump = state.mem.allocValue();
auto vDump = evaluator.mem.allocValue();
vDump->mkString(toplevel.dumpCli());
auto vRes = state.mem.allocValue();
state.callFunction(*vGenerateManpage, state.builtins.get("false"), *vRes, noPos);
state.callFunction(*vRes, *vDump, *vRes, noPos);
auto vRes = evaluator.mem.allocValue();
state->callFunction(*vGenerateManpage, evaluator.builtins.get("false"), *vRes, noPos);
state->callFunction(*vRes, *vDump, *vRes, noPos);
auto attr = vRes->attrs->get(state.symbols.create(mdName + ".md"));
auto attr = vRes->attrs->get(evaluator.symbols.create(mdName + ".md"));
if (!attr)
throw UsageError("`nix` has no subcommand '%s'", concatStringsSep("", subcommand));
auto markdown = state.forceString(*attr->value, noPos, "while evaluating the lowdown help text");
auto markdown = state->forceString(*attr->value, noPos, "while evaluating the lowdown help text");
RunPager pager;
std::cout << renderMarkdownToTerminal(markdown) << "\n";
+7 -6
View File
@@ -185,9 +185,10 @@ static int main_nix_prefetch_url(std::string programName, Strings argv)
setLogFormat(LogFormat::bar);
auto store = openStore();
auto state = std::make_unique<EvalState>(myArgs.searchPath, store);
auto evaluator = std::make_unique<EvalState>(myArgs.searchPath, store);
auto & state = evaluator;
Bindings & autoArgs = *myArgs.getAutoArgs(*state);
Bindings & autoArgs = *myArgs.getAutoArgs(*evaluator);
/* If -A is given, get the URL from the specified Nix
expression. */
@@ -200,13 +201,13 @@ static int main_nix_prefetch_url(std::string programName, Strings argv)
Value vRoot;
state->evalFile(
resolveExprPath(
lookupFileArg(*state, args.empty() ? "." : args[0])),
lookupFileArg(*evaluator, args.empty() ? "." : args[0])),
vRoot);
Value & v(*findAlongAttrPath(*state, attrPath, autoArgs, vRoot).first);
state->forceAttrs(v, noPos, "while evaluating the source attribute to prefetch");
/* Extract the URL. */
auto * attr = v.attrs->get(state->symbols.create("urls"));
auto * attr = v.attrs->get(evaluator->symbols.create("urls"));
if (!attr)
throw Error("attribute 'urls' missing");
state->forceList(*attr->value, noPos, "while evaluating the urls to prefetch");
@@ -215,7 +216,7 @@ static int main_nix_prefetch_url(std::string programName, Strings argv)
url = state->forceString(*attr->value->listElems()[0], noPos, "while evaluating the first url from the urls list");
/* Extract the hash mode. */
auto attr2 = v.attrs->get(state->symbols.create("outputHashMode"));
auto attr2 = v.attrs->get(evaluator->symbols.create("outputHashMode"));
if (!attr2)
printInfo("warning: this does not look like a fetchurl call");
else
@@ -223,7 +224,7 @@ static int main_nix_prefetch_url(std::string programName, Strings argv)
/* Extract the name. */
if (!name) {
auto attr3 = v.attrs->get(state->symbols.create("name"));
auto attr3 = v.attrs->get(evaluator->symbols.create("name"));
if (!attr3)
name = state->forceString(*attr3->value, noPos, "while evaluating the name of the source to prefetch");
}
+5 -4
View File
@@ -63,7 +63,8 @@ struct CmdRepl : RawInstallablesCommand
void run(ref<Store> store, std::vector<std::string> && rawInstallables) override
{
auto state = getEvalState();
auto evaluator = getEvalState();
auto state = evaluator;
auto getValues = [&]()->AbstractNixRepl::AnnotatedValues{
auto installables = parseInstallables(store, rawInstallables);
AbstractNixRepl::AnnotatedValues values;
@@ -74,8 +75,8 @@ struct CmdRepl : RawInstallablesCommand
auto [val, pos] = installable.toValue();
auto what = installable.what();
state->forceValue(*val, pos);
auto autoArgs = getAutoArgs(*state);
auto valPost = state->mem.allocValue();
auto autoArgs = getAutoArgs(*evaluator);
auto valPost = evaluator->mem.allocValue();
state->autoCallFunction(*autoArgs, *val, *valPost);
state->forceValue(*valPost, pos);
values.push_back( {valPost, what });
@@ -86,7 +87,7 @@ struct CmdRepl : RawInstallablesCommand
}
return values;
};
AbstractNixRepl::run(searchPath, openStore(), *state, getValues, {}, getAutoArgs(*state));
AbstractNixRepl::run(searchPath, openStore(), *state, getValues, {}, getAutoArgs(*evaluator));
}
};
+2 -1
View File
@@ -84,7 +84,8 @@ struct CmdSearch : InstallableCommand, MixJSON
for (auto & re : excludeRes)
excludeRegexes.emplace_back(re, std::regex::extended | std::regex::icase);
auto state = getEvalState();
auto evaluator = getEvalState();
auto state = evaluator;
std::optional<nlohmann::json> jsonOut;
if (json) jsonOut = json::object();
+5 -4
View File
@@ -288,10 +288,11 @@ struct CmdUpgradeNix : MixDryRun, EvalCommand
auto [res, content] = getFileTransfer()->download(storePathsUrl);
auto data = content->drain();
auto state = std::make_unique<EvalState>(SearchPath{}, store);
auto v = state->mem.allocValue();
state->eval(state->parseExprFromString(data, CanonPath("/no-such-path")), *v);
Bindings & bindings(*state->mem.allocBindings(0));
auto evaluator = std::make_unique<EvalState>(SearchPath{}, store);
auto & state = evaluator;
auto v = evaluator->mem.allocValue();
state->eval(evaluator->parseExprFromString(data, CanonPath("/no-such-path")), *v);
Bindings & bindings(*evaluator->mem.allocBindings(0));
auto v2 = findAlongAttrPath(*state, settings.thisSystem, bindings, *v).first;
return store->parseStorePath(state->forceString(*v2, noPos, "while evaluating the path tho latest nix version"));
+6 -7
View File
@@ -31,25 +31,24 @@ TEST(Arguments, lookupFileArg) {
searchPath.elements.push_back(SearchPath::Elem::parse(searchPathElem));
auto store = openStore("dummy://");
auto statePtr = std::make_shared<EvalState>(searchPath, store, store);
auto & state = *statePtr;
auto state = std::make_shared<EvalState>(searchPath, store, store);
SourcePath const foundUnitData = lookupFileArg(state, "<example>");
SourcePath const foundUnitData = lookupFileArg(*state, "<example>");
EXPECT_EQ(foundUnitData.path, canonDataPath);
// lookupFileArg should not resolve <search paths> if anything else is before or after it.
SourcePath const yepEvenSpaces = lookupFileArg(state, " <example>");
SourcePath const yepEvenSpaces = lookupFileArg(*state, " <example>");
EXPECT_EQ(yepEvenSpaces.path, CanonPath::fromCwd(" <example>"));
EXPECT_EQ(lookupFileArg(state, "<example>/nixos").path, CanonPath::fromCwd("<example>/nixos"));
EXPECT_EQ(lookupFileArg(*state, "<example>/nixos").path, CanonPath::fromCwd("<example>/nixos"));
try {
lookupFileArg(state, INVALID_CHANNEL);
lookupFileArg(*state, INVALID_CHANNEL);
} catch (FileTransferError const & ex) {
std::string_view const msg(ex.what());
EXPECT_NE(msg.find(CHANNEL_URL), msg.npos);
}
SourcePath const normalFile = lookupFileArg(state, unitDataPath);
SourcePath const normalFile = lookupFileArg(*state, unitDataPath);
EXPECT_EQ(normalFile.path, canonDataPath);
}
+6 -4
View File
@@ -23,12 +23,13 @@ namespace nix {
protected:
LibExprTest()
: LibStoreTest()
, state({}, store)
, evaluator({}, store)
, state(evaluator)
{
}
Value eval(std::string input, bool forceValue = true, const FeatureSettings & fSettings = featureSettings) {
Value v;
Expr & e = state.parseExprFromString(input, CanonPath::root, fSettings);
Expr & e = evaluator.parseExprFromString(input, CanonPath::root, fSettings);
state.eval(e, v);
if (forceValue)
state.forceValue(v, noPos);
@@ -36,10 +37,11 @@ namespace nix {
}
Symbol createSymbol(const char * value) {
return state.symbols.create(value);
return evaluator.symbols.create(value);
}
EvalState state;
EvalState evaluator;
EvalState & state;
};
MATCHER(IsListType, "") {
+4 -4
View File
@@ -25,8 +25,8 @@ RC_GTEST_FIXTURE_PROP(
prop_opaque_path_round_trip,
(const SingleDerivedPath::Opaque & o))
{
auto * v = state.mem.allocValue();
state.paths.mkStorePathString(o.path, *v);
auto * v = evaluator.mem.allocValue();
evaluator.paths.mkStorePathString(o.path, *v);
auto d = state.coerceToSingleDerivedPath(noPos, *v, "");
RC_ASSERT(SingleDerivedPath { o } == d);
}
@@ -46,7 +46,7 @@ RC_GTEST_FIXTURE_PROP(
ExperimentalFeatureSettings mockXpSettings;
mockXpSettings.set("experimental-features", "ca-derivations");
auto * v = state.mem.allocValue();
auto * v = evaluator.mem.allocValue();
state.mkOutputString(*v, b, std::nullopt, mockXpSettings);
auto [d, _] = state.coerceToSingleDerivedPathUnchecked(noPos, *v, "");
RC_ASSERT(SingleDerivedPath { b } == d);
@@ -57,7 +57,7 @@ RC_GTEST_FIXTURE_PROP(
prop_derived_path_built_out_path_round_trip,
(const SingleDerivedPath::Built & b, const StorePath & outPath))
{
auto * v = state.mem.allocValue();
auto * v = evaluator.mem.allocValue();
state.mkOutputString(*v, b, outPath);
auto [d, _] = state.coerceToSingleDerivedPathUnchecked(noPos, *v, "");
RC_ASSERT(SingleDerivedPath { b } == d);
+7 -7
View File
@@ -12,21 +12,21 @@ namespace nix {
TEST_F(ErrorTraceTest, TraceBuilder) {
ASSERT_THROW(
state.errors.make<EvalError>("puppy").debugThrow(),
evaluator.errors.make<EvalError>("puppy").debugThrow(),
EvalError
);
ASSERT_THROW(
state.errors.make<EvalError>("puppy").withTrace(noPos, "doggy").debugThrow(),
evaluator.errors.make<EvalError>("puppy").withTrace(noPos, "doggy").debugThrow(),
EvalError
);
ASSERT_THROW(
try {
try {
state.errors.make<EvalError>("puppy").withTrace(noPos, "doggy").debugThrow();
evaluator.errors.make<EvalError>("puppy").withTrace(noPos, "doggy").debugThrow();
} catch (Error & e) {
e.addTrace(state.positions[noPos], "beans");
e.addTrace(evaluator.positions[noPos], "beans");
throw;
}
} catch (BaseError & e) {
@@ -47,12 +47,12 @@ namespace nix {
TEST_F(ErrorTraceTest, NestedThrows) {
try {
state.errors.make<EvalError>("puppy").withTrace(noPos, "doggy").debugThrow();
evaluator.errors.make<EvalError>("puppy").withTrace(noPos, "doggy").debugThrow();
} catch (BaseError & e) {
try {
state.errors.make<EvalError>("beans").debugThrow();
evaluator.errors.make<EvalError>("beans").debugThrow();
} catch (Error & e2) {
e.addTrace(state.positions[noPos], "beans2");
e.addTrace(evaluator.positions[noPos], "beans2");
//e2.addTrace(state.positions[noPos], "Something", "");
ASSERT_TRUE(e.info().traces.size() == 2);
ASSERT_TRUE(e2.info().traces.size() == 0);
+2 -2
View File
@@ -17,7 +17,7 @@ struct ExprPrintingTests : LibExprTest
void test(Expr const & expr, std::string_view expected)
{
std::stringstream out;
expr.show(state.symbols, out);
expr.show(evaluator.symbols, out);
ASSERT_EQ(out.str(), expected);
}
};
@@ -26,7 +26,7 @@ TEST_F(ExprPrintingTests, ExprInheritFrom)
{
// ExprInheritFrom has its own show() impl.
// If it uses its parent class's impl it will crash.
auto inheritSource = make_ref<ExprVar>(state.symbols.create("stdenv"));
auto inheritSource = make_ref<ExprVar>(evaluator.symbols.create("stdenv"));
ExprInheritFrom const eInheritFrom(noPos, 0, inheritSource);
test(eInheritFrom, "(/* expanded inherit (expr) */ stdenv)");
}
+56 -56
View File
@@ -61,9 +61,9 @@ TEST_F(ValuePrintingTests, tAttrs)
Value vTwo;
vTwo.mkInt(2);
BindingsBuilder builder = state.buildBindings(10);
builder.insert(state.symbols.create("one"), &vOne);
builder.insert(state.symbols.create("two"), &vTwo);
BindingsBuilder builder = evaluator.buildBindings(10);
builder.insert(evaluator.symbols.create("one"), &vOne);
builder.insert(evaluator.symbols.create("two"), &vTwo);
Value vAttrs;
vAttrs.mkAttrs(builder.finish());
@@ -79,7 +79,7 @@ TEST_F(ValuePrintingTests, tList)
Value vTwo;
vTwo.mkInt(2);
Value vList = state.mem.newList(5);
Value vList = evaluator.mem.newList(5);
vList.bigList.elems[0] = &vOne;
vList.bigList.elems[1] = &vTwo;
vList.bigList.size = 3;
@@ -110,8 +110,8 @@ TEST_F(ValuePrintingTests, vLambda)
.up = nullptr,
.values = { }
};
PosTable::Origin origin = state.positions.addOrigin(std::monostate(), 1);
auto posIdx = state.positions.add(origin, 0);
PosTable::Origin origin = evaluator.positions.addOrigin(std::monostate(), 1);
auto posIdx = evaluator.positions.add(origin, 0);
ExprLambda eLambda(posIdx, createSymbol("a"), std::make_unique<Formals>(), std::make_unique<ExprInt>(0));
@@ -201,28 +201,28 @@ TEST_F(ValuePrintingTests, depthAttrs)
Value vTwo;
vTwo.mkInt(2);
BindingsBuilder builderEmpty = state.buildBindings(0);
BindingsBuilder builderEmpty = evaluator.buildBindings(0);
Value vAttrsEmpty;
vAttrsEmpty.mkAttrs(builderEmpty.finish());
BindingsBuilder builderNested = state.buildBindings(1);
builderNested.insert(state.symbols.create("zero"), &vZero);
BindingsBuilder builderNested = evaluator.buildBindings(1);
builderNested.insert(evaluator.symbols.create("zero"), &vZero);
Value vAttrsNested;
vAttrsNested.mkAttrs(builderNested.finish());
BindingsBuilder builder = state.buildBindings(10);
builder.insert(state.symbols.create("one"), &vOne);
builder.insert(state.symbols.create("two"), &vTwo);
builder.insert(state.symbols.create("empty"), &vAttrsEmpty);
builder.insert(state.symbols.create("nested"), &vAttrsNested);
BindingsBuilder builder = evaluator.buildBindings(10);
builder.insert(evaluator.symbols.create("one"), &vOne);
builder.insert(evaluator.symbols.create("two"), &vTwo);
builder.insert(evaluator.symbols.create("empty"), &vAttrsEmpty);
builder.insert(evaluator.symbols.create("nested"), &vAttrsNested);
Value vAttrs;
vAttrs.mkAttrs(builder.finish());
BindingsBuilder builder2 = state.buildBindings(10);
builder2.insert(state.symbols.create("one"), &vOne);
builder2.insert(state.symbols.create("two"), &vTwo);
builder2.insert(state.symbols.create("nested"), &vAttrs);
BindingsBuilder builder2 = evaluator.buildBindings(10);
builder2.insert(evaluator.symbols.create("one"), &vOne);
builder2.insert(evaluator.symbols.create("two"), &vTwo);
builder2.insert(evaluator.symbols.create("nested"), &vAttrs);
Value vNested;
vNested.mkAttrs(builder2.finish());
@@ -241,22 +241,22 @@ TEST_F(ValuePrintingTests, depthList)
Value vTwo;
vTwo.mkInt(2);
BindingsBuilder builder = state.buildBindings(10);
builder.insert(state.symbols.create("one"), &vOne);
builder.insert(state.symbols.create("two"), &vTwo);
BindingsBuilder builder = evaluator.buildBindings(10);
builder.insert(evaluator.symbols.create("one"), &vOne);
builder.insert(evaluator.symbols.create("two"), &vTwo);
Value vAttrs;
vAttrs.mkAttrs(builder.finish());
BindingsBuilder builder2 = state.buildBindings(10);
builder2.insert(state.symbols.create("one"), &vOne);
builder2.insert(state.symbols.create("two"), &vTwo);
builder2.insert(state.symbols.create("nested"), &vAttrs);
BindingsBuilder builder2 = evaluator.buildBindings(10);
builder2.insert(evaluator.symbols.create("one"), &vOne);
builder2.insert(evaluator.symbols.create("two"), &vTwo);
builder2.insert(evaluator.symbols.create("nested"), &vAttrs);
Value vNested;
vNested.mkAttrs(builder2.finish());
Value vList = state.mem.newList(5);
Value vList = evaluator.mem.newList(5);
vList.bigList.elems[0] = &vOne;
vList.bigList.elems[1] = &vTwo;
vList.bigList.elems[2] = &vNested;
@@ -304,9 +304,9 @@ TEST_F(ValuePrintingTests, attrsTypeFirst)
Value vApple;
vApple.mkString("apple");
BindingsBuilder builder = state.buildBindings(10);
builder.insert(state.symbols.create("type"), &vType);
builder.insert(state.symbols.create("apple"), &vApple);
BindingsBuilder builder = evaluator.buildBindings(10);
builder.insert(evaluator.symbols.create("type"), &vType);
builder.insert(evaluator.symbols.create("apple"), &vApple);
Value vAttrs;
vAttrs.mkAttrs(builder.finish());
@@ -415,9 +415,9 @@ TEST_F(ValuePrintingTests, ansiColorsAttrs)
Value vTwo;
vTwo.mkInt(2);
BindingsBuilder builder = state.buildBindings(10);
builder.insert(state.symbols.create("one"), &vOne);
builder.insert(state.symbols.create("two"), &vTwo);
BindingsBuilder builder = evaluator.buildBindings(10);
builder.insert(evaluator.symbols.create("one"), &vOne);
builder.insert(evaluator.symbols.create("two"), &vTwo);
Value vAttrs;
vAttrs.mkAttrs(builder.finish());
@@ -434,8 +434,8 @@ TEST_F(ValuePrintingTests, ansiColorsDerivation)
Value vDerivation;
vDerivation.mkString("derivation");
BindingsBuilder builder = state.buildBindings(10);
builder.insert(state.s.type, &vDerivation);
BindingsBuilder builder = evaluator.buildBindings(10);
builder.insert(evaluator.s.type, &vDerivation);
Value vAttrs;
vAttrs.mkAttrs(builder.finish());
@@ -459,7 +459,7 @@ TEST_F(ValuePrintingTests, ansiColorsDerivation)
TEST_F(ValuePrintingTests, ansiColorsError)
{
Value vError;
auto & e = state.parseExprFromString("{ a = throw \"uh oh!\"; }", {CanonPath::root});
auto & e = evaluator.parseExprFromString("{ a = throw \"uh oh!\"; }", {CanonPath::root});
state.eval(e, vError);
test(*vError.attrs->begin()->value,
@@ -475,7 +475,7 @@ TEST_F(ValuePrintingTests, ansiColorsError)
TEST_F(ValuePrintingTests, ansiColorsDerivationError)
{
Value vAttrs;
auto & e = state.parseExprFromString(
auto & e = evaluator.parseExprFromString(
"{ type = \"derivation\"; drvPath = throw \"uh oh!\"; }", {CanonPath::root}
);
state.eval(e, vAttrs);
@@ -508,7 +508,7 @@ TEST_F(ValuePrintingTests, ansiColorsDerivationError)
TEST_F(ValuePrintingTests, ansiColorsAssert)
{
auto & e = state.parseExprFromString("{ a = assert false; 1; }", {CanonPath::root});
auto & e = evaluator.parseExprFromString("{ a = assert false; 1; }", {CanonPath::root});
Value v;
state.eval(e, v);
@@ -529,7 +529,7 @@ TEST_F(ValuePrintingTests, ansiColorsList)
Value vTwo;
vTwo.mkInt(2);
Value vList = state.mem.newList(5);
Value vList = evaluator.mem.newList(5);
vList.bigList.elems[0] = &vOne;
vList.bigList.elems[1] = &vTwo;
vList.bigList.size = 3;
@@ -547,8 +547,8 @@ TEST_F(ValuePrintingTests, ansiColorsLambda)
.up = nullptr,
.values = { }
};
PosTable::Origin origin = state.positions.addOrigin(std::monostate(), 1);
auto posIdx = state.positions.add(origin, 0);
PosTable::Origin origin = evaluator.positions.addOrigin(std::monostate(), 1);
auto posIdx = evaluator.positions.add(origin, 0);
ExprLambda eLambda(posIdx, createSymbol("a"), std::make_unique<Formals>(), std::make_unique<ExprInt>(0));
@@ -635,15 +635,15 @@ TEST_F(ValuePrintingTests, ansiColorsAttrsRepeated)
Value vZero;
vZero.mkInt(0);
BindingsBuilder innerBuilder = state.buildBindings(1);
innerBuilder.insert(state.symbols.create("x"), &vZero);
BindingsBuilder innerBuilder = evaluator.buildBindings(1);
innerBuilder.insert(evaluator.symbols.create("x"), &vZero);
Value vInner;
vInner.mkAttrs(innerBuilder.finish());
BindingsBuilder builder = state.buildBindings(10);
builder.insert(state.symbols.create("a"), &vInner);
builder.insert(state.symbols.create("b"), &vInner);
BindingsBuilder builder = evaluator.buildBindings(10);
builder.insert(evaluator.symbols.create("a"), &vInner);
builder.insert(evaluator.symbols.create("b"), &vInner);
Value vAttrs;
vAttrs.mkAttrs(builder.finish());
@@ -660,13 +660,13 @@ TEST_F(ValuePrintingTests, ansiColorsListRepeated)
Value vZero;
vZero.mkInt(0);
BindingsBuilder innerBuilder = state.buildBindings(1);
innerBuilder.insert(state.symbols.create("x"), &vZero);
BindingsBuilder innerBuilder = evaluator.buildBindings(1);
innerBuilder.insert(evaluator.symbols.create("x"), &vZero);
Value vInner;
vInner.mkAttrs(innerBuilder.finish());
Value vList = state.mem.newList(3);
Value vList = evaluator.mem.newList(3);
vList.bigList.elems[0] = &vInner;
vList.bigList.elems[1] = &vInner;
vList.bigList.size = 2;
@@ -683,13 +683,13 @@ TEST_F(ValuePrintingTests, listRepeated)
Value vZero;
vZero.mkInt(0);
BindingsBuilder innerBuilder = state.buildBindings(1);
innerBuilder.insert(state.symbols.create("x"), &vZero);
BindingsBuilder innerBuilder = evaluator.buildBindings(1);
innerBuilder.insert(evaluator.symbols.create("x"), &vZero);
Value vInner;
vInner.mkAttrs(innerBuilder.finish());
Value vList = state.mem.newList(3);
Value vList = evaluator.mem.newList(3);
vList.bigList.elems[0] = &vInner;
vList.bigList.elems[1] = &vInner;
vList.bigList.size = 2;
@@ -710,9 +710,9 @@ TEST_F(ValuePrintingTests, ansiColorsAttrsElided)
Value vTwo;
vTwo.mkInt(2);
BindingsBuilder builder = state.buildBindings(10);
builder.insert(state.symbols.create("one"), &vOne);
builder.insert(state.symbols.create("two"), &vTwo);
BindingsBuilder builder = evaluator.buildBindings(10);
builder.insert(evaluator.symbols.create("one"), &vOne);
builder.insert(evaluator.symbols.create("two"), &vTwo);
Value vAttrs;
vAttrs.mkAttrs(builder.finish());
@@ -727,7 +727,7 @@ TEST_F(ValuePrintingTests, ansiColorsAttrsElided)
Value vThree;
vThree.mkInt(3);
builder.insert(state.symbols.create("three"), &vThree);
builder.insert(evaluator.symbols.create("three"), &vThree);
vAttrs.mkAttrs(builder.finish());
test(vAttrs,
@@ -746,7 +746,7 @@ TEST_F(ValuePrintingTests, ansiColorsListElided)
Value vTwo;
vTwo.mkInt(2);
Value vList = state.mem.newList(4);
Value vList = evaluator.mem.newList(4);
vList.bigList.elems[0] = &vOne;
vList.bigList.elems[1] = &vTwo;
vList.bigList.size = 2;