Derivation v2 #16884
GROQ_API_KEY / GROQ_API_KEY_backup in .env
@@ -0,0 +1,60 @@
+# Version 2 derivations
+
+
+**Experimental feature**: [Version 2] derivations are experimental, and so is this function.
+
+`builtins.derivationStrictV2` creates a [version 2] derivation.
+Unlike `derivation`, it does not take a flat attribute set whose attributes double as environment variables.
+Each part of the derivation has an attribute of its own, so environment variables are only environment variables, and options are only options:
+
+```nix
+builtins.derivationStrictV2 {
+ name = "hello";
+ system = "x86_64-linux";
+ builder = "${bash}/bin/bash";
+ args = [ "-c" "..." ];
+ env = {
+ out = builtins.placeholder "out";
+ src = "${src}";
+ big = { value = "..."; passAsFile = true; };
+ };
+ outputs = {
+ out = {
+ method = "nar";
If we already define a new derivation type, is NAR really the hash that we want? Why not a tree hash that can be parallelized?
@@ -0,0 +1,390 @@
+#include "nix/expr/primops.hh"
+#include "nix/expr/eval-inline.hh"
+#include "nix/expr/eval-settings.hh"
+#include "nix/store/derivation/v2/convert.hh"
+#include "nix/store/downstream-placeholder.hh"
+#include "nix/store/globals.hh"
+#include "nix/store/store-api.hh"
+
+namespace nix {
+
+using namespace derivation::v2;
+
+namespace {
+
+/**
+ * Turns strings with context into interpolated strings: each store path
+ * or placeholder its context accounts for becomes a reference to the
+ * input, or own output, it stands for.
+ */
+struct Interpolator
+{
+ EvalState & state;
+ std::string_view drvName;
+ PathOf staticPathOf;
+
+ /**
+ * Keys are the strings that stand for references in the evaluator's
+ * strings: own-output placeholders, input placeholders, and the
+ * store paths of inputs.
+ */
+ std::map<std::string, Reference<SingleDerivedPath>> keys;
+
+ std::set<SingleDerivedPath> inputs;
+
+ void addOutput(const OutputName & name)
+ {
+ keys.emplace(hashPlaceholder(name), Reference<SingleDerivedPath>{name});
+ }
+
+ void addContext(const NixStringContext & context)
+ {
+ for (auto & c : context)
+ std::visit(
+ overloaded{
+ [&](const NixStringContextElem::Opaque & o) {
+ state.ensureLazyPathCopied(o.path);
+ SingleDerivedPath p = SingleDerivedPath::Opaque{.path = o.path};
+ inputs.insert(p);
+ keys.emplace(state.store->printStorePath(o.path), Reference<SingleDerivedPath>{p});
+ },
+ [&](const NixStringContextElem::Built & b) {
+ SingleDerivedPath::Built built{.drvPath = b.drvPath, .output = b.output};
+ SingleDerivedPath p = built;
+ inputs.insert(p);
+ keys.emplace(
+ DownstreamPlaceholder::fromSingleDerivedPathBuilt(built).render(),
+ Reference<SingleDerivedPath>{p});
+ if (auto path = staticPathOf(built))
+ keys.emplace(state.store->printStorePath(*path), Reference<SingleDerivedPath>{p});
+ },
+ [&](const NixStringContextElem::DrvDeep & d) {
+ /* A version 2 derivation says exactly what it depends
+ on, so there is no depending on a derivation's whole
+ closure, outputs included, in one go. */
+ state
+ .error<EvalError>(
+ "string refers to the derivation '%s' together with its whole closure, which "
+ "version 2 derivations cannot depend on; depend on the outputs needed instead, "
+ "or on the derivation alone with 'builtins.unsafeDiscardOutputDependency'",
+ state.store->printStorePath(d.drvPath))
+ .debugThrow();
+ },
+ },
+ c.raw);
+ }
+
+ Interpolated<SingleDerivedPath> interpolate(std::string_view s) const
+ {
+ Interpolated<SingleDerivedPath> res;
+ while (!s.empty()) {
+ size_t best = std::string_view::npos;
+ const std::pair<const std::string, Reference<SingleDerivedPath>> * which = nullptr;
+ for (auto & entry : keys) {
+ auto i = s.find(entry.first);
+ if (i < best || (i == best && which && entry.first.size() > which->first.size())) {
+ best = i;
+ which = &entry;
+ }
+ }
+ if (!which) {
+ res.append(std::string{s});
+ break;
+ }
+ res.append(std::string{s.substr(0, best)});
+ res.append(which->second);
+ s.remove_prefix(best + which->first.size());
+ }
+ return res;
+ }
+
+ /**
+ * Evaluate a string, and interpolate it.
+ */
+ Interpolated<SingleDerivedPath> string(Value & v, std::string_view what)
+ {
+ NixStringContext context;
+ auto s = state.coerceToString(noPos, v, context, what, false, true).toOwned();
+ addContext(context);
+ return interpolate(s);
+ }
+
+ /**
+ * Evaluate a string that must refer to exactly one thing: an own
+ * output by name, or an input by its store path or placeholder.
+ */
+ Reference<SingleDerivedPath> reference(Value & v, std::string_view what, const std::set<OutputName> & outputs)
+ {
+ NixStringContext context;
+ auto s = state.coerceToString(noPos, v, context, what, false, true).toOwned();
+ if (context.empty()) {
+ if (!outputs.contains(s))
+ state.error<EvalError>("'%s' %s is neither an output name nor a store path", s, what).debugThrow();
+ return OutputName{s};
+ }
+ addContext(context);
+ auto i = keys.find(s);
+ if (i == keys.end())
+ state.error<EvalError>("'%s' %s does not refer to exactly one input", s, what).debugThrow();
+ return i->second;
+ }
+
+ SingleDerivedPath input(Value & v, std::string_view what)
+ {
+ auto ref = reference(v, what, {});
+ auto * p = std::get_if<SingleDerivedPath>(&ref);
+ if (!p)
+ state.error<EvalError>("%s must refer to an input", what).debugThrow();
+ return *p;
+ }
+};
+
+} // namespace
+
+static StringSet forceStrings(EvalState & state, Value & v, std::string_view what)
+{
+ state.forceList(v, noPos, what);
+ StringSet res;
+ for (auto * elem : v.listView())
+ res.insert(std::string{state.forceStringNoCtx(*elem, noPos, what)});
+ return res;
+}
+
+static void prim_derivationStrictV2(EvalState & state, CallSite callSite, Value * const * args, Value & v)
+{
+
+ std::string_view errorCtx = "while evaluating the argument passed to builtins.derivationStrictV2";
+ state.forceAttrs(*args[0], noPos, errorCtx);
+ auto attrs = args[0]->attrs();
+
+ auto get = [&](std::string_view name) -> Value * {
+ auto * a = attrs->get(state.symbols.create(name));
+ return a ? a->value : nullptr;
+ };
+ auto require = [&](std::string_view name) -> Value & {
+ auto * a = get(name);
+ if (!a)
+ state.error<EvalError>("required attribute '%s' missing", name).debugThrow();
+ return *a;
+ };
+
+ Full drv{
+ .name = std::string{state.forceStringNoCtx(require("name"), noPos, "while evaluating the 'name' attribute")},
+ .platform =
+ std::string{state.forceStringNoCtx(require("system"), noPos, "while evaluating the 'system' attribute")},
+ };
+
+ try {
+ Interpolator interp{
+ .state = state,
+ .drvName = drv.name,
+ .staticPathOf = staticPathOf(*state.store),
+ };
+
+ /* The outputs first, so that the strings can refer to them. */
+ auto & outputsV = require("outputs");
+ state.forceAttrs(outputsV, noPos, "while evaluating the 'outputs' attribute");
+ std::set<OutputName> outputNames;
+ for (auto & a : *outputsV.attrs())
+ outputNames.insert(std::string{state.symbols[a.name]});
+ if (outputNames.empty())
+ state.error<EvalError>("a derivation must have at least one output").debugThrow();
+ for (auto & name : outputNames)
+ interp.addOutput(name);
+
+ drv.builder = interp.string(require("builder"), "while evaluating the 'builder' attribute");
+
+ if (auto * argsV = get("args")) {
+ state.forceList(*argsV, noPos, "while evaluating the 'args' attribute");
+ for (auto * a : argsV->listView())
+ drv.args.push_back(interp.string(*a, "while evaluating an element of the 'args' attribute"));
+ }
+
+ if (auto * envV = get("env")) {
+ state.forceAttrs(*envV, noPos, "while evaluating the 'env' attribute");
+ for (auto & a : *envV->attrs()) {
+ std::string name{state.symbols[a.name]};
+ state.forceValue(*a.value, noPos);
+ EnvVar<SingleDerivedPath> var;
+ if (a.value->type() == nAttrs) {
+ auto * valueA = a.value->attrs()->get(state.symbols.create("value"));
+ if (!valueA)
+ state.error<EvalError>("environment variable '%s' has no 'value'", name).debugThrow();
+ var.value = interp.string(*valueA->value, "while evaluating an environment variable");
+ if (auto * pf = a.value->attrs()->get(state.symbols.create("passAsFile")))
+ var.passAsFile = state.forceBool(*pf->value, noPos, "while evaluating 'passAsFile'");
+ } else {
+ var.value = interp.string(*a.value, "while evaluating an environment variable");
+ }
+ drv.env.emplace(std::move(name), std::move(var));
+ }
+ }
+
+ for (auto & a : *outputsV.attrs()) {
+ std::string outputName{state.symbols[a.name]};
+ state.forceAttrs(*a.value, noPos, "while evaluating an output");
+ auto * o = a.value->attrs();
+ auto field = [&](std::string_view f) -> Value * {
+ auto * x = o->get(state.symbols.create(f));
+ return x ? x->value : nullptr;
+ };
+
+ Output<SingleDerivedPath> output{.raw = InputAddressed{}};
+ auto * method = field("method");
+ auto * hashAlgo = field("hashAlgo");
+ if (auto * hash = field("hash")) {
+ if (!method)
+ state.error<EvalError>("output '%s' needs 'method' as well as 'hash'", outputName).debugThrow();
+ if (outputName != "out" || outputsV.attrs()->size() != 1)
+ state
+ .error<EvalError>(
+ "a derivation with a fixed content-addressed output must have just the one output 'out'")
+ .debugThrow();
+ auto m = ContentAddressMethod::parse(state.forceStringNoCtx(*method, noPos, "while evaluating 'method'"));
+ std::optional<HashAlgorithm> h;
+ if (hashAlgo)
+ h = parseHashAlgo(state.forceStringNoCtx(*hashAlgo, noPos, "while evaluating 'hashAlgo'"));
+ output.raw = derivation::Output::CAFixed{
+ .ca =
+ {
+ .method = std::move(m),
+ .hash = Hash::parseAny(state.forceStringNoCtx(*hash, noPos, "while evaluating 'hash'"), h),
+ },
+ };
+ } else if (method || hashAlgo) {
+ if (!method || !hashAlgo)
+ state.error<EvalError>("output '%s' needs both 'method' and 'hashAlgo'", outputName).debugThrow();
+ auto m = ContentAddressMethod::parse(state.forceStringNoCtx(*method, noPos, "while evaluating 'method'"));
+ auto h = parseHashAlgo(state.forceStringNoCtx(*hashAlgo, noPos, "while evaluating 'hashAlgo'"));
+ auto * impure = field("impure");
+ if (impure && state.forceBool(*impure, noPos, "while evaluating 'impure'")) {
+ experimentalFeatureSettings.require(Xp::ImpureDerivations);
+ output.raw = derivation::Output::Impure{.method = std::move(m), .hashAlgo = h};
+ } else {
+ experimentalFeatureSettings.require(Xp::CaDerivations);
+ output.raw = derivation::Output::CAFloating{.method = std::move(m), .hashAlgo = h};
+ }
+ }
+
+ if (auto * optsV = field("options")) {
+ state.forceAttrs(*optsV, noPos, "while evaluating an output's 'options'");
+ auto & c = output.options.checks;
+ auto refs = [&](Value & l, std::string_view what) {
+ state.forceList(l, noPos, what);
+ std::set<Reference<SingleDerivedPath>> res;
+ for (auto * e : l.listView())
+ res.insert(interp.reference(*e, what, outputNames));
+ return res;
+ };
+ for (auto & opt : *optsV->attrs()) {
+ std::string_view name = state.symbols[opt.name];
+ auto & ov = *opt.value;
+ if (name == "allowedReferences")
+ c.allowedReferences = refs(ov, "in 'allowedReferences'");
+ else if (name == "allowedRequisites")
+ c.allowedRequisites = refs(ov, "in 'allowedRequisites'");
+ else if (name == "disallowedReferences")
+ c.disallowedReferences = refs(ov, "in 'disallowedReferences'");
+ else if (name == "disallowedRequisites")
+ c.disallowedRequisites = refs(ov, "in 'disallowedRequisites'");
+ else if (name == "ignoreSelfRefs")
+ c.ignoreSelfRefs = state.forceBool(ov, noPos, "while evaluating 'ignoreSelfRefs'");
+ else if (name == "maxSize")
+ c.maxSize = state.forceInt(ov, noPos, "while evaluating 'maxSize'").value;
+ else if (name == "maxClosureSize")
+ c.maxClosureSize = state.forceInt(ov, noPos, "while evaluating 'maxClosureSize'").value;
+ else if (name == "unsafeDiscardReferences")
+ output.options.unsafeDiscardReferences =
+ state.forceBool(ov, noPos, "while evaluating 'unsafeDiscardReferences'");
+ else
+ state.error<EvalError>("unknown output option '%s'", name).debugThrow();
+ }
+ }
+
+ drv.outputs.emplace(std::move(outputName), std::move(output));
+ }
+
+ if (auto * optsV = get("options")) {
+ state.forceAttrs(*optsV, noPos, "while evaluating the 'options' attribute");
+ auto & o = drv.options;
+ for (auto & opt : *optsV->attrs()) {
+ std::string_view name = state.symbols[opt.name];
+ auto & ov = *opt.value;
+ auto what = fmt("while evaluating the option '%s'", name);
+ if (name == "additionalSandboxProfile")
+ o.additionalSandboxProfile = std::string{state.forceStringNoCtx(ov, noPos, what)};
+ else if (name == "allowLocalNetworking")
+ o.allowLocalNetworking = state.forceBool(ov, noPos, what);
+ else if (name == "allowSubstitutes")
+ o.allowSubstitutes = state.forceBool(ov, noPos, what);
+ else if (name == "exportReferencesGraph") {
+ state.forceAttrs(ov, noPos, what);
+ for (auto & e : *ov.attrs()) {
+ state.forceList(*e.value, noPos, what);
+ std::set<SingleDerivedPath> paths;
+ for (auto * p : e.value->listView())
+ paths.insert(interp.input(*p, "in 'exportReferencesGraph'"));
+ o.exportReferencesGraph.emplace(std::string{state.symbols[e.name]}, std::move(paths));
+ }
+ } else if (name == "impureEnvVars")
+ o.impureEnvVars = forceStrings(state, ov, what);
+ else if (name == "impureHostDeps")
+ o.impureHostDeps = forceStrings(state, ov, what);
+ else if (name == "noChroot")
+ o.noChroot = state.forceBool(ov, noPos, what);
+ else if (name == "preferLocalBuild")
+ o.preferLocalBuild = state.forceBool(ov, noPos, what);
+ else if (name == "requiredSystemFeatures")
+ o.requiredSystemFeatures = forceStrings(state, ov, what);
+ else
+ state.error<EvalError>("unknown option '%s'", name).debugThrow();
+ }
+ }
+
+ drv.inputs = derivation::FullInputs::fromSet(interp.inputs);
+ } catch (Error & e) {
+ e.addTrace(nullptr, HintFmt("while evaluating derivation '%s'", drv.name), TracePrint::Always);
+ throw;
+ }
+
+ auto drvPath = settings.readOnlyMode ? computeStorePath(*state.store, drv)
+ : writeDerivation(*state.store, drv, state.repair);
+ auto outputPaths = staticOutputPaths(*state.store, drv, staticPathOf(*state.store));
+
+ /* The derivation path refers to just the derivation, not to its
+ closure with outputs as the `drvPath` of `derivation` does. */
+ auto result = state.buildBindings(1 + drv.outputs.size());
+ result.alloc(state.s.drvPath)
+ .mkString(
+ state.store->printStorePath(drvPath),
+ {
+ NixStringContextElem::Opaque{.path = drvPath},
+ },
+ state.mem);
+ for (auto & [outputName, output] : drv.outputs) {
+ std::optional<StorePath> path;
+ if (outputPaths)
+ if (auto i = outputPaths->find(outputName); i != outputPaths->end())
+ path = i->second;
+ state.mkOutputString(
+ result.alloc(outputName),
+ SingleDerivedPath::Built{
+ .drvPath = makeConstantStorePathRef(drvPath),
+ .output = outputName,
+ },
+ path);
+ }
+ v.mkAttrs(result);
+}
+
+static RegisterPrimOp primop_derivationStrictV2({
+ .name = "__derivationStrictV2",
+ .args = {"attrs"},
+ .doc = R"(
+ Create a [version 2 derivation](@docroot@/language/derivations/v2.md).
+ )",
+ .impl = prim_derivationStrictV2,
+ .experimentalFeature = Xp::DerivationsV2,
Do we really want more experimental features? We don't have any roadmap on getting them "stable" for years now. I don't think this is sustainable.
@@ -0,0 +1,167 @@
+# Version 2 derivation "ATerm" format
+
+This is the form of [version 2] derivations in the [derivation "ATerm" format](../derivation-aterm.md), whose [common productions](../derivation-aterm.md#common) it uses.
+
+**Experimental feature**: [Version 2] derivations, and so this form, are experimental, and may change.
+
+Version 2 derivations represent their [options](@docroot@/store/derivation/index.md#options) and the [*pass as file*](@docroot@/store/derivation/index.md#pass-as-file) flags of their environment variables directly, and so do the references in their strings:
+
+```ebnf
+derivation-v2 = 'DrvWithVersion("v2",' outputs-v2 "," input-drvs-v2 "," input-srcs ","
+ platform "," builder-v2 "," args-v2 "," env-v2 "," options ")" ;
+```
+
+## Interpolated strings {#interpolated}
+
+The [builder](@docroot@/store/derivation/index.md#builder), [arguments](@docroot@/store/derivation/index.md#args), and environment variable values of a version 2 derivation are not plain strings, but lists of *pieces*, each either literal text or a reference:
+
+```ebnf
+interpolated = list(piece) ;
an example here on top would help readability for each grammar.
@@ -0,0 +1,95 @@
+# Derivation versions
+
+There are two versions of [derivations][store derivation].
+They agree on what a derivation *means* --- the [parts] it consists of --- but differ in how much of it is represented directly.
+
+The version of a derivation is part of it: two derivations of different versions are different derivations, even if they mean the same thing.
+Each version has its own form in the ["ATerm" format][aterm].
+
+## Version 1 {#version-1}
+
+Version 1 derivations are the derivations Nix has always had.
+They are the only stable version at this time.
+
+The [inputs] of version 1 derivations are always first-order, and the store paths of their outputs are always known in advance, though why they are known depends on the [type](#versions-and-types) of the derivation.
+A version 1 derivation cannot depend on a version 2 derivation: its input derivations are always version 1 derivations too.
+So the store paths of all its inputs are known in advance, and it never needs to refer to one that is not, which is why version 1 derivations need no input [placeholders].
+The [input addresses][input-addressing] of version 1 derivations are computed by [masking].
+
+Their [options] are not represented directly.
+Instead they are *encoded*, in one of two ways, which give the two *modes* of version 1 derivations:
+
+- Without [structured attributes], options are encoded as specially-named [environment variables].
+- With structured attributes, options are encoded as specially-named attributes in them.
+
+Either way, options are encoded amidst freeform data that is to be passed to the [builder], "stealing" certain values by giving them special meanings in addition to the env vars and JSON file they affect.
+The encoding is the source of truth: the options of a version 1 derivation cannot be varied independently of the data they are parsed from.
+Not every option can be encoded in both modes; see [Options][options].
+
+## Version 2 {#version-2}
+
+**Experimental feature**: Version 2 derivations, and so all the kinds of derivation that require them, are experimental.
+
+Version 2 derivations represent everything directly.
+Their [options] are fields of the derivation in their own right, just like the [builder] or the [arguments][args], and so is the [*pass as file*][pass-as-file] flag of each environment variable.
+Every option can be set, including those that version 1 derivations can only encode with structured attributes.
+Only the richer structured-attributes-mode options are supported, in fact.
+
+Version 2 derivations do not have structured attributes.
+This is because structured attributes are a layer violation.
+
+> **Explanation**
+>
+> The reason that environment variables are supported by Nix is because they are an inherent OS level concept to the processes being run.
+> Environment variables are not reducible to some other concept because they are a primitive building block on Unix and Windows --- that is simply how the interface of those operating systems is defined.
+> JSON and the bash interpreting it, however, are purely.
Typo.
@@ -0,0 +1,390 @@
+#include "nix/expr/primops.hh"
+#include "nix/expr/eval-inline.hh"
+#include "nix/expr/eval-settings.hh"
+#include "nix/store/derivation/v2/convert.hh"
+#include "nix/store/downstream-placeholder.hh"
+#include "nix/store/globals.hh"
+#include "nix/store/store-api.hh"
+
+namespace nix {
+
+using namespace derivation::v2;
+
+namespace {
+
+/**
+ * Turns strings with context into interpolated strings: each store path
+ * or placeholder its context accounts for becomes a reference to the
+ * input, or own output, it stands for.
+ */
+struct Interpolator
+{
+ EvalState & state;
+ std::string_view drvName;
+ PathOf staticPathOf;
+
+ /**
+ * Keys are the strings that stand for references in the evaluator's
+ * strings: own-output placeholders, input placeholders, and the
+ * store paths of inputs.
+ */
+ std::map<std::string, Reference<SingleDerivedPath>> keys;
+
+ std::set<SingleDerivedPath> inputs;
+
+ void addOutput(const OutputName & name)
+ {
+ keys.emplace(hashPlaceholder(name), Reference<SingleDerivedPath>{name});
+ }
+
+ void addContext(const NixStringContext & context)
+ {
+ for (auto & c : context)
+ std::visit(
+ overloaded{
+ [&](const NixStringContextElem::Opaque & o) {
+ state.ensureLazyPathCopied(o.path);
+ SingleDerivedPath p = SingleDerivedPath::Opaque{.path = o.path};
+ inputs.insert(p);
+ keys.emplace(state.store->printStorePath(o.path), Reference<SingleDerivedPath>{p});
+ },
+ [&](const NixStringContextElem::Built & b) {
+ SingleDerivedPath::Built built{.drvPath = b.drvPath, .output = b.output};
+ SingleDerivedPath p = built;
+ inputs.insert(p);
+ keys.emplace(
+ DownstreamPlaceholder::fromSingleDerivedPathBuilt(built).render(),
+ Reference<SingleDerivedPath>{p});
+ if (auto path = staticPathOf(built))
+ keys.emplace(state.store->printStorePath(*path), Reference<SingleDerivedPath>{p});
+ },
+ [&](const NixStringContextElem::DrvDeep & d) {
+ /* A version 2 derivation says exactly what it depends
+ on, so there is no depending on a derivation's whole
+ closure, outputs included, in one go. */
+ state
+ .error<EvalError>(
+ "string refers to the derivation '%s' together with its whole closure, which "
+ "version 2 derivations cannot depend on; depend on the outputs needed instead, "
+ "or on the derivation alone with 'builtins.unsafeDiscardOutputDependency'",
+ state.store->printStorePath(d.drvPath))
+ .debugThrow();
+ },
+ },
+ c.raw);
+ }
+
+ Interpolated<SingleDerivedPath> interpolate(std::string_view s) const
+ {
+ Interpolated<SingleDerivedPath> res;
+ while (!s.empty()) {
+ size_t best = std::string_view::npos;
+ const std::pair<const std::string, Reference<SingleDerivedPath>> * which = nullptr;
+ for (auto & entry : keys) {
+ auto i = s.find(entry.first);
+ if (i < best || (i == best && which && entry.first.size() > which->first.size())) {
+ best = i;
+ which = &entry;
+ }
+ }
+ if (!which) {
+ res.append(std::string{s});
+ break;
+ }
+ res.append(std::string{s.substr(0, best)});
+ res.append(which->second);
+ s.remove_prefix(best + which->first.size());
+ }
+ return res;
+ }
+
+ /**
+ * Evaluate a string, and interpolate it.
+ */
+ Interpolated<SingleDerivedPath> string(Value & v, std::string_view what)
+ {
+ NixStringContext context;
+ auto s = state.coerceToString(noPos, v, context, what, false, true).toOwned();
+ addContext(context);
+ return interpolate(s);
+ }
+
+ /**
+ * Evaluate a string that must refer to exactly one thing: an own
+ * output by name, or an input by its store path or placeholder.
+ */
+ Reference<SingleDerivedPath> reference(Value & v, std::string_view what, const std::set<OutputName> & outputs)
+ {
+ NixStringContext context;
+ auto s = state.coerceToString(noPos, v, context, what, false, true).toOwned();
+ if (context.empty()) {
+ if (!outputs.contains(s))
+ state.error<EvalError>("'%s' %s is neither an output name nor a store path", s, what).debugThrow();
+ return OutputName{s};
+ }
+ addContext(context);
+ auto i = keys.find(s);
+ if (i == keys.end())
+ state.error<EvalError>("'%s' %s does not refer to exactly one input", s, what).debugThrow();
+ return i->second;
+ }
+
+ SingleDerivedPath input(Value & v, std::string_view what)
+ {
+ auto ref = reference(v, what, {});
+ auto * p = std::get_if<SingleDerivedPath>(&ref);
+ if (!p)
+ state.error<EvalError>("%s must refer to an input", what).debugThrow();
+ return *p;
+ }
+};
+
+} // namespace
+
+static StringSet forceStrings(EvalState & state, Value & v, std::string_view what)
+{
+ state.forceList(v, noPos, what);
+ StringSet res;
+ for (auto * elem : v.listView())
+ res.insert(std::string{state.forceStringNoCtx(*elem, noPos, what)});
+ return res;
+}
+
+static void prim_derivationStrictV2(EvalState & state, CallSite callSite, Value * const * args, Value & v)
+{
+
+ std::string_view errorCtx = "while evaluating the argument passed to builtins.derivationStrictV2";
+ state.forceAttrs(*args[0], noPos, errorCtx);
+ auto attrs = args[0]->attrs();
+
+ auto get = [&](std::string_view name) -> Value * {
+ auto * a = attrs->get(state.symbols.create(name));
+ return a ? a->value : nullptr;
+ };
+ auto require = [&](std::string_view name) -> Value & {
+ auto * a = get(name);
+ if (!a)
+ state.error<EvalError>("required attribute '%s' missing", name).debugThrow();
+ return *a;
+ };
+
+ Full drv{
+ .name = std::string{state.forceStringNoCtx(require("name"), noPos, "while evaluating the 'name' attribute")},
+ .platform =
+ std::string{state.forceStringNoCtx(require("system"), noPos, "while evaluating the 'system' attribute")},
+ };
+
+ try {
+ Interpolator interp{
+ .state = state,
+ .drvName = drv.name,
+ .staticPathOf = staticPathOf(*state.store),
+ };
+
+ /* The outputs first, so that the strings can refer to them. */
+ auto & outputsV = require("outputs");
+ state.forceAttrs(outputsV, noPos, "while evaluating the 'outputs' attribute");
+ std::set<OutputName> outputNames;
+ for (auto & a : *outputsV.attrs())
+ outputNames.insert(std::string{state.symbols[a.name]});
+ if (outputNames.empty())
+ state.error<EvalError>("a derivation must have at least one output").debugThrow();
+ for (auto & name : outputNames)
+ interp.addOutput(name);
+
+ drv.builder = interp.string(require("builder"), "while evaluating the 'builder' attribute");
+
+ if (auto * argsV = get("args")) {
+ state.forceList(*argsV, noPos, "while evaluating the 'args' attribute");
+ for (auto * a : argsV->listView())
+ drv.args.push_back(interp.string(*a, "while evaluating an element of the 'args' attribute"));
+ }
+
+ if (auto * envV = get("env")) {
+ state.forceAttrs(*envV, noPos, "while evaluating the 'env' attribute");
+ for (auto & a : *envV->attrs()) {
+ std::string name{state.symbols[a.name]};
+ state.forceValue(*a.value, noPos);
+ EnvVar<SingleDerivedPath> var;
+ if (a.value->type() == nAttrs) {
+ auto * valueA = a.value->attrs()->get(state.symbols.create("value"));
+ if (!valueA)
+ state.error<EvalError>("environment variable '%s' has no 'value'", name).debugThrow();
+ var.value = interp.string(*valueA->value, "while evaluating an environment variable");
+ if (auto * pf = a.value->attrs()->get(state.symbols.create("passAsFile")))
+ var.passAsFile = state.forceBool(*pf->value, noPos, "while evaluating 'passAsFile'");
+ } else {
+ var.value = interp.string(*a.value, "while evaluating an environment variable");
+ }
+ drv.env.emplace(std::move(name), std::move(var));
+ }
+ }
+
+ for (auto & a : *outputsV.attrs()) {
+ std::string outputName{state.symbols[a.name]};
+ state.forceAttrs(*a.value, noPos, "while evaluating an output");
+ auto * o = a.value->attrs();
+ auto field = [&](std::string_view f) -> Value * {
+ auto * x = o->get(state.symbols.create(f));
+ return x ? x->value : nullptr;
+ };
+
+ Output<SingleDerivedPath> output{.raw = InputAddressed{}};
+ auto * method = field("method");
+ auto * hashAlgo = field("hashAlgo");
+ if (auto * hash = field("hash")) {
+ if (!method)
+ state.error<EvalError>("output '%s' needs 'method' as well as 'hash'", outputName).debugThrow();
+ if (outputName != "out" || outputsV.attrs()->size() != 1)
+ state
+ .error<EvalError>(
+ "a derivation with a fixed content-addressed output must have just the one output 'out'")
+ .debugThrow();
+ auto m = ContentAddressMethod::parse(state.forceStringNoCtx(*method, noPos, "while evaluating 'method'"));
+ std::optional<HashAlgorithm> h;
+ if (hashAlgo)
+ h = parseHashAlgo(state.forceStringNoCtx(*hashAlgo, noPos, "while evaluating 'hashAlgo'"));
+ output.raw = derivation::Output::CAFixed{
+ .ca =
+ {
+ .method = std::move(m),
+ .hash = Hash::parseAny(state.forceStringNoCtx(*hash, noPos, "while evaluating 'hash'"), h),
+ },
+ };
+ } else if (method || hashAlgo) {
+ if (!method || !hashAlgo)
+ state.error<EvalError>("output '%s' needs both 'method' and 'hashAlgo'", outputName).debugThrow();
+ auto m = ContentAddressMethod::parse(state.forceStringNoCtx(*method, noPos, "while evaluating 'method'"));
+ auto h = parseHashAlgo(state.forceStringNoCtx(*hashAlgo, noPos, "while evaluating 'hashAlgo'"));
+ auto * impure = field("impure");
+ if (impure && state.forceBool(*impure, noPos, "while evaluating 'impure'")) {
+ experimentalFeatureSettings.require(Xp::ImpureDerivations);
+ output.raw = derivation::Output::Impure{.method = std::move(m), .hashAlgo = h};
+ } else {
+ experimentalFeatureSettings.require(Xp::CaDerivations);
+ output.raw = derivation::Output::CAFloating{.method = std::move(m), .hashAlgo = h};
+ }
+ }
+
+ if (auto * optsV = field("options")) {
+ state.forceAttrs(*optsV, noPos, "while evaluating an output's 'options'");
+ auto & c = output.options.checks;
+ auto refs = [&](Value & l, std::string_view what) {
+ state.forceList(l, noPos, what);
+ std::set<Reference<SingleDerivedPath>> res;
+ for (auto * e : l.listView())
+ res.insert(interp.reference(*e, what, outputNames));
+ return res;
+ };
+ for (auto & opt : *optsV->attrs()) {
+ std::string_view name = state.symbols[opt.name];
+ auto & ov = *opt.value;
+ if (name == "allowedReferences")
+ c.allowedReferences = refs(ov, "in 'allowedReferences'");
+ else if (name == "allowedRequisites")
+ c.allowedRequisites = refs(ov, "in 'allowedRequisites'");
+ else if (name == "disallowedReferences")
+ c.disallowedReferences = refs(ov, "in 'disallowedReferences'");
+ else if (name == "disallowedRequisites")
+ c.disallowedRequisites = refs(ov, "in 'disallowedRequisites'");
+ else if (name == "ignoreSelfRefs")
+ c.ignoreSelfRefs = state.forceBool(ov, noPos, "while evaluating 'ignoreSelfRefs'");
+ else if (name == "maxSize")
+ c.maxSize = state.forceInt(ov, noPos, "while evaluating 'maxSize'").value;
+ else if (name == "maxClosureSize")
+ c.maxClosureSize = state.forceInt(ov, noPos, "while evaluating 'maxClosureSize'").value;
+ else if (name == "unsafeDiscardReferences")
+ output.options.unsafeDiscardReferences =
+ state.forceBool(ov, noPos, "while evaluating 'unsafeDiscardReferences'");
+ else
+ state.error<EvalError>("unknown output option '%s'", name).debugThrow();
+ }
+ }
+
+ drv.outputs.emplace(std::move(outputName), std::move(output));
+ }
+
+ if (auto * optsV = get("options")) {
+ state.forceAttrs(*optsV, noPos, "while evaluating the 'options' attribute");
+ auto & o = drv.options;
+ for (auto & opt : *optsV->attrs()) {
+ std::string_view name = state.symbols[opt.name];
+ auto & ov = *opt.value;
+ auto what = fmt("while evaluating the option '%s'", name);
+ if (name == "additionalSandboxProfile")
+ o.additionalSandboxProfile = std::string{state.forceStringNoCtx(ov, noPos, what)};
+ else if (name == "allowLocalNetworking")
+ o.allowLocalNetworking = state.forceBool(ov, noPos, what);
+ else if (name == "allowSubstitutes")
+ o.allowSubstitutes = state.forceBool(ov, noPos, what);
+ else if (name == "exportReferencesGraph") {
+ state.forceAttrs(ov, noPos, what);
+ for (auto & e : *ov.attrs()) {
+ state.forceList(*e.value, noPos, what);
+ std::set<SingleDerivedPath> paths;
+ for (auto * p : e.value->listView())
+ paths.insert(interp.input(*p, "in 'exportReferencesGraph'"));
+ o.exportReferencesGraph.emplace(std::string{state.symbols[e.name]}, std::move(paths));
+ }
+ } else if (name == "impureEnvVars")
+ o.impureEnvVars = forceStrings(state, ov, what);
+ else if (name == "impureHostDeps")
+ o.impureHostDeps = forceStrings(state, ov, what);
+ else if (name == "noChroot")
+ o.noChroot = state.forceBool(ov, noPos, what);
+ else if (name == "preferLocalBuild")
+ o.preferLocalBuild = state.forceBool(ov, noPos, what);
+ else if (name == "requiredSystemFeatures")
+ o.requiredSystemFeatures = forceStrings(state, ov, what);
+ else
+ state.error<EvalError>("unknown option '%s'", name).debugThrow();
+ }
+ }
+
+ drv.inputs = derivation::FullInputs::fromSet(interp.inputs);
+ } catch (Error & e) {
+ e.addTrace(nullptr, HintFmt("while evaluating derivation '%s'", drv.name), TracePrint::Always);
+ throw;
+ }
+
+ auto drvPath = settings.readOnlyMode ? computeStorePath(*state.store, drv)
+ : writeDerivation(*state.store, drv, state.repair);
+ auto outputPaths = staticOutputPaths(*state.store, drv, staticPathOf(*state.store));
+
+ /* The derivation path refers to just the derivation, not to its
+ closure with outputs as the `drvPath` of `derivation` does. */
+ auto result = state.buildBindings(1 + drv.outputs.size());
+ result.alloc(state.s.drvPath)
+ .mkString(
+ state.store->printStorePath(drvPath),
+ {
+ NixStringContextElem::Opaque{.path = drvPath},
+ },
+ state.mem);
+ for (auto & [outputName, output] : drv.outputs) {
+ std::optional<StorePath> path;
+ if (outputPaths)
+ if (auto i = outputPaths->find(outputName); i != outputPaths->end())
+ path = i->second;
+ state.mkOutputString(
+ result.alloc(outputName),
+ SingleDerivedPath::Built{
+ .drvPath = makeConstantStorePathRef(drvPath),
+ .output = outputName,
+ },
+ path);
+ }
+ v.mkAttrs(result);
+}
+
+static RegisterPrimOp primop_derivationStrictV2({
+ .name = "__derivationStrictV2",
+ .args = {"attrs"},
+ .doc = R"(
+ Create a [version 2 derivation](@docroot@/language/derivations/v2.md).
+ )",
+ .impl = prim_derivationStrictV2,
+ .experimentalFeature = Xp::DerivationsV2,
@roberth please give me more context why you disagreeing with this? I think our focus is wrong that we that we don't put more effort into getting rid of "experiments" or declare them part of nix and instead just let the list of experimental features grow longer.
@@ -0,0 +1,60 @@
+# Version 2 derivations
+
+
+**Experimental feature**: [Version 2] derivations are experimental, and so is this function.
+
+`builtins.derivationStrictV2` creates a [version 2] derivation.
+Unlike `derivation`, it does not take a flat attribute set whose attributes double as environment variables.
+Each part of the derivation has an attribute of its own, so environment variables are only environment variables, and options are only options:
+
+```nix
+builtins.derivationStrictV2 {
+ name = "hello";
+ system = "x86_64-linux";
+ builder = "${bash}/bin/bash";
+ args = [ "-c" "..." ];
+ env = {
+ out = builtins.placeholder "out";
+ src = "${src}";
+ big = { value = "..."; passAsFile = true; };
+ };
+ outputs = {
+ out = {
+ method = "nar";
we already do have a git tree hash, could we also add this right after this PR?
That would add a strong motivation for changing a v2 derivation format. Parsing json is nice but I don't think the drv format is really a big bottleneck in eval compared to json.
@@ -0,0 +1,60 @@
+# Version 2 derivations
+
+
+**Experimental feature**: [Version 2] derivations are experimental, and so is this function.
+
+`builtins.derivationStrictV2` creates a [version 2] derivation.
+Unlike `derivation`, it does not take a flat attribute set whose attributes double as environment variables.
+Each part of the derivation has an attribute of its own, so environment variables are only environment variables, and options are only options:
+
+```nix
+builtins.derivationStrictV2 {
+ name = "hello";
+ system = "x86_64-linux";
+ builder = "${bash}/bin/bash";
+ args = [ "-c" "..." ];
+ env = {
+ out = builtins.placeholder "out";
+ src = "${src}";
+ big = { value = "..."; passAsFile = true; };
+ };
+ outputs = {
+ out = {
+ method = "nar";
Ignore. this is for derivations not content-addressed inputs.
@@ -0,0 +1,390 @@
+#include "nix/expr/primops.hh"
+#include "nix/expr/eval-inline.hh"
+#include "nix/expr/eval-settings.hh"
+#include "nix/store/derivation/v2/convert.hh"
+#include "nix/store/downstream-placeholder.hh"
+#include "nix/store/globals.hh"
+#include "nix/store/store-api.hh"
+
+namespace nix {
+
+using namespace derivation::v2;
+
+namespace {
+
+/**
+ * Turns strings with context into interpolated strings: each store path
+ * or placeholder its context accounts for becomes a reference to the
+ * input, or own output, it stands for.
+ */
+struct Interpolator
+{
+ EvalState & state;
+ std::string_view drvName;
+ PathOf staticPathOf;
+
+ /**
+ * Keys are the strings that stand for references in the evaluator's
+ * strings: own-output placeholders, input placeholders, and the
+ * store paths of inputs.
+ */
+ std::map<std::string, Reference<SingleDerivedPath>> keys;
+
+ std::set<SingleDerivedPath> inputs;
+
+ void addOutput(const OutputName & name)
+ {
+ keys.emplace(hashPlaceholder(name), Reference<SingleDerivedPath>{name});
+ }
+
+ void addContext(const NixStringContext & context)
+ {
+ for (auto & c : context)
+ std::visit(
+ overloaded{
+ [&](const NixStringContextElem::Opaque & o) {
+ state.ensureLazyPathCopied(o.path);
+ SingleDerivedPath p = SingleDerivedPath::Opaque{.path = o.path};
+ inputs.insert(p);
+ keys.emplace(state.store->printStorePath(o.path), Reference<SingleDerivedPath>{p});
+ },
+ [&](const NixStringContextElem::Built & b) {
+ SingleDerivedPath::Built built{.drvPath = b.drvPath, .output = b.output};
+ SingleDerivedPath p = built;
+ inputs.insert(p);
+ keys.emplace(
+ DownstreamPlaceholder::fromSingleDerivedPathBuilt(built).render(),
+ Reference<SingleDerivedPath>{p});
+ if (auto path = staticPathOf(built))
+ keys.emplace(state.store->printStorePath(*path), Reference<SingleDerivedPath>{p});
+ },
+ [&](const NixStringContextElem::DrvDeep & d) {
+ /* A version 2 derivation says exactly what it depends
+ on, so there is no depending on a derivation's whole
+ closure, outputs included, in one go. */
+ state
+ .error<EvalError>(
+ "string refers to the derivation '%s' together with its whole closure, which "
+ "version 2 derivations cannot depend on; depend on the outputs needed instead, "
+ "or on the derivation alone with 'builtins.unsafeDiscardOutputDependency'",
+ state.store->printStorePath(d.drvPath))
+ .debugThrow();
+ },
+ },
+ c.raw);
+ }
+
+ Interpolated<SingleDerivedPath> interpolate(std::string_view s) const
+ {
+ Interpolated<SingleDerivedPath> res;
+ while (!s.empty()) {
+ size_t best = std::string_view::npos;
+ const std::pair<const std::string, Reference<SingleDerivedPath>> * which = nullptr;
+ for (auto & entry : keys) {
+ auto i = s.find(entry.first);
+ if (i < best || (i == best && which && entry.first.size() > which->first.size())) {
+ best = i;
+ which = &entry;
+ }
+ }
+ if (!which) {
+ res.append(std::string{s});
+ break;
+ }
+ res.append(std::string{s.substr(0, best)});
+ res.append(which->second);
+ s.remove_prefix(best + which->first.size());
+ }
+ return res;
+ }
+
+ /**
+ * Evaluate a string, and interpolate it.
+ */
+ Interpolated<SingleDerivedPath> string(Value & v, std::string_view what)
+ {
+ NixStringContext context;
+ auto s = state.coerceToString(noPos, v, context, what, false, true).toOwned();
+ addContext(context);
+ return interpolate(s);
+ }
+
+ /**
+ * Evaluate a string that must refer to exactly one thing: an own
+ * output by name, or an input by its store path or placeholder.
+ */
+ Reference<SingleDerivedPath> reference(Value & v, std::string_view what, const std::set<OutputName> & outputs)
+ {
+ NixStringContext context;
+ auto s = state.coerceToString(noPos, v, context, what, false, true).toOwned();
+ if (context.empty()) {
+ if (!outputs.contains(s))
+ state.error<EvalError>("'%s' %s is neither an output name nor a store path", s, what).debugThrow();
+ return OutputName{s};
+ }
+ addContext(context);
+ auto i = keys.find(s);
+ if (i == keys.end())
+ state.error<EvalError>("'%s' %s does not refer to exactly one input", s, what).debugThrow();
+ return i->second;
+ }
+
+ SingleDerivedPath input(Value & v, std::string_view what)
+ {
+ auto ref = reference(v, what, {});
+ auto * p = std::get_if<SingleDerivedPath>(&ref);
+ if (!p)
+ state.error<EvalError>("%s must refer to an input", what).debugThrow();
+ return *p;
+ }
+};
+
+} // namespace
+
+static StringSet forceStrings(EvalState & state, Value & v, std::string_view what)
+{
+ state.forceList(v, noPos, what);
+ StringSet res;
+ for (auto * elem : v.listView())
+ res.insert(std::string{state.forceStringNoCtx(*elem, noPos, what)});
+ return res;
+}
+
+static void prim_derivationStrictV2(EvalState & state, CallSite callSite, Value * const * args, Value & v)
+{
+
+ std::string_view errorCtx = "while evaluating the argument passed to builtins.derivationStrictV2";
+ state.forceAttrs(*args[0], noPos, errorCtx);
+ auto attrs = args[0]->attrs();
+
+ auto get = [&](std::string_view name) -> Value * {
+ auto * a = attrs->get(state.symbols.create(name));
+ return a ? a->value : nullptr;
+ };
+ auto require = [&](std::string_view name) -> Value & {
+ auto * a = get(name);
+ if (!a)
+ state.error<EvalError>("required attribute '%s' missing", name).debugThrow();
+ return *a;
+ };
+
+ Full drv{
+ .name = std::string{state.forceStringNoCtx(require("name"), noPos, "while evaluating the 'name' attribute")},
+ .platform =
+ std::string{state.forceStringNoCtx(require("system"), noPos, "while evaluating the 'system' attribute")},
+ };
+
+ try {
+ Interpolator interp{
+ .state = state,
+ .drvName = drv.name,
+ .staticPathOf = staticPathOf(*state.store),
+ };
+
+ /* The outputs first, so that the strings can refer to them. */
+ auto & outputsV = require("outputs");
+ state.forceAttrs(outputsV, noPos, "while evaluating the 'outputs' attribute");
+ std::set<OutputName> outputNames;
+ for (auto & a : *outputsV.attrs())
+ outputNames.insert(std::string{state.symbols[a.name]});
+ if (outputNames.empty())
+ state.error<EvalError>("a derivation must have at least one output").debugThrow();
+ for (auto & name : outputNames)
+ interp.addOutput(name);
+
+ drv.builder = interp.string(require("builder"), "while evaluating the 'builder' attribute");
+
+ if (auto * argsV = get("args")) {
+ state.forceList(*argsV, noPos, "while evaluating the 'args' attribute");
+ for (auto * a : argsV->listView())
+ drv.args.push_back(interp.string(*a, "while evaluating an element of the 'args' attribute"));
+ }
+
+ if (auto * envV = get("env")) {
+ state.forceAttrs(*envV, noPos, "while evaluating the 'env' attribute");
+ for (auto & a : *envV->attrs()) {
+ std::string name{state.symbols[a.name]};
+ state.forceValue(*a.value, noPos);
+ EnvVar<SingleDerivedPath> var;
+ if (a.value->type() == nAttrs) {
+ auto * valueA = a.value->attrs()->get(state.symbols.create("value"));
+ if (!valueA)
+ state.error<EvalError>("environment variable '%s' has no 'value'", name).debugThrow();
+ var.value = interp.string(*valueA->value, "while evaluating an environment variable");
+ if (auto * pf = a.value->attrs()->get(state.symbols.create("passAsFile")))
+ var.passAsFile = state.forceBool(*pf->value, noPos, "while evaluating 'passAsFile'");
+ } else {
+ var.value = interp.string(*a.value, "while evaluating an environment variable");
+ }
+ drv.env.emplace(std::move(name), std::move(var));
+ }
+ }
+
+ for (auto & a : *outputsV.attrs()) {
+ std::string outputName{state.symbols[a.name]};
+ state.forceAttrs(*a.value, noPos, "while evaluating an output");
+ auto * o = a.value->attrs();
+ auto field = [&](std::string_view f) -> Value * {
+ auto * x = o->get(state.symbols.create(f));
+ return x ? x->value : nullptr;
+ };
+
+ Output<SingleDerivedPath> output{.raw = InputAddressed{}};
+ auto * method = field("method");
+ auto * hashAlgo = field("hashAlgo");
+ if (auto * hash = field("hash")) {
+ if (!method)
+ state.error<EvalError>("output '%s' needs 'method' as well as 'hash'", outputName).debugThrow();
+ if (outputName != "out" || outputsV.attrs()->size() != 1)
+ state
+ .error<EvalError>(
+ "a derivation with a fixed content-addressed output must have just the one output 'out'")
+ .debugThrow();
+ auto m = ContentAddressMethod::parse(state.forceStringNoCtx(*method, noPos, "while evaluating 'method'"));
+ std::optional<HashAlgorithm> h;
+ if (hashAlgo)
+ h = parseHashAlgo(state.forceStringNoCtx(*hashAlgo, noPos, "while evaluating 'hashAlgo'"));
+ output.raw = derivation::Output::CAFixed{
+ .ca =
+ {
+ .method = std::move(m),
+ .hash = Hash::parseAny(state.forceStringNoCtx(*hash, noPos, "while evaluating 'hash'"), h),
+ },
+ };
+ } else if (method || hashAlgo) {
+ if (!method || !hashAlgo)
+ state.error<EvalError>("output '%s' needs both 'method' and 'hashAlgo'", outputName).debugThrow();
+ auto m = ContentAddressMethod::parse(state.forceStringNoCtx(*method, noPos, "while evaluating 'method'"));
+ auto h = parseHashAlgo(state.forceStringNoCtx(*hashAlgo, noPos, "while evaluating 'hashAlgo'"));
+ auto * impure = field("impure");
+ if (impure && state.forceBool(*impure, noPos, "while evaluating 'impure'")) {
+ experimentalFeatureSettings.require(Xp::ImpureDerivations);
+ output.raw = derivation::Output::Impure{.method = std::move(m), .hashAlgo = h};
+ } else {
+ experimentalFeatureSettings.require(Xp::CaDerivations);
+ output.raw = derivation::Output::CAFloating{.method = std::move(m), .hashAlgo = h};
+ }
+ }
+
+ if (auto * optsV = field("options")) {
+ state.forceAttrs(*optsV, noPos, "while evaluating an output's 'options'");
+ auto & c = output.options.checks;
+ auto refs = [&](Value & l, std::string_view what) {
+ state.forceList(l, noPos, what);
+ std::set<Reference<SingleDerivedPath>> res;
+ for (auto * e : l.listView())
+ res.insert(interp.reference(*e, what, outputNames));
+ return res;
+ };
+ for (auto & opt : *optsV->attrs()) {
+ std::string_view name = state.symbols[opt.name];
+ auto & ov = *opt.value;
+ if (name == "allowedReferences")
+ c.allowedReferences = refs(ov, "in 'allowedReferences'");
+ else if (name == "allowedRequisites")
+ c.allowedRequisites = refs(ov, "in 'allowedRequisites'");
+ else if (name == "disallowedReferences")
+ c.disallowedReferences = refs(ov, "in 'disallowedReferences'");
+ else if (name == "disallowedRequisites")
+ c.disallowedRequisites = refs(ov, "in 'disallowedRequisites'");
+ else if (name == "ignoreSelfRefs")
+ c.ignoreSelfRefs = state.forceBool(ov, noPos, "while evaluating 'ignoreSelfRefs'");
+ else if (name == "maxSize")
+ c.maxSize = state.forceInt(ov, noPos, "while evaluating 'maxSize'").value;
+ else if (name == "maxClosureSize")
+ c.maxClosureSize = state.forceInt(ov, noPos, "while evaluating 'maxClosureSize'").value;
+ else if (name == "unsafeDiscardReferences")
+ output.options.unsafeDiscardReferences =
+ state.forceBool(ov, noPos, "while evaluating 'unsafeDiscardReferences'");
+ else
+ state.error<EvalError>("unknown output option '%s'", name).debugThrow();
+ }
+ }
+
+ drv.outputs.emplace(std::move(outputName), std::move(output));
+ }
+
+ if (auto * optsV = get("options")) {
+ state.forceAttrs(*optsV, noPos, "while evaluating the 'options' attribute");
+ auto & o = drv.options;
+ for (auto & opt : *optsV->attrs()) {
+ std::string_view name = state.symbols[opt.name];
+ auto & ov = *opt.value;
+ auto what = fmt("while evaluating the option '%s'", name);
+ if (name == "additionalSandboxProfile")
+ o.additionalSandboxProfile = std::string{state.forceStringNoCtx(ov, noPos, what)};
+ else if (name == "allowLocalNetworking")
+ o.allowLocalNetworking = state.forceBool(ov, noPos, what);
+ else if (name == "allowSubstitutes")
+ o.allowSubstitutes = state.forceBool(ov, noPos, what);
+ else if (name == "exportReferencesGraph") {
+ state.forceAttrs(ov, noPos, what);
+ for (auto & e : *ov.attrs()) {
+ state.forceList(*e.value, noPos, what);
+ std::set<SingleDerivedPath> paths;
+ for (auto * p : e.value->listView())
+ paths.insert(interp.input(*p, "in 'exportReferencesGraph'"));
+ o.exportReferencesGraph.emplace(std::string{state.symbols[e.name]}, std::move(paths));
+ }
+ } else if (name == "impureEnvVars")
+ o.impureEnvVars = forceStrings(state, ov, what);
+ else if (name == "impureHostDeps")
+ o.impureHostDeps = forceStrings(state, ov, what);
+ else if (name == "noChroot")
+ o.noChroot = state.forceBool(ov, noPos, what);
+ else if (name == "preferLocalBuild")
+ o.preferLocalBuild = state.forceBool(ov, noPos, what);
+ else if (name == "requiredSystemFeatures")
+ o.requiredSystemFeatures = forceStrings(state, ov, what);
+ else
+ state.error<EvalError>("unknown option '%s'", name).debugThrow();
+ }
+ }
+
+ drv.inputs = derivation::FullInputs::fromSet(interp.inputs);
+ } catch (Error & e) {
+ e.addTrace(nullptr, HintFmt("while evaluating derivation '%s'", drv.name), TracePrint::Always);
+ throw;
+ }
+
+ auto drvPath = settings.readOnlyMode ? computeStorePath(*state.store, drv)
+ : writeDerivation(*state.store, drv, state.repair);
+ auto outputPaths = staticOutputPaths(*state.store, drv, staticPathOf(*state.store));
+
+ /* The derivation path refers to just the derivation, not to its
+ closure with outputs as the `drvPath` of `derivation` does. */
+ auto result = state.buildBindings(1 + drv.outputs.size());
+ result.alloc(state.s.drvPath)
+ .mkString(
+ state.store->printStorePath(drvPath),
+ {
+ NixStringContextElem::Opaque{.path = drvPath},
+ },
+ state.mem);
+ for (auto & [outputName, output] : drv.outputs) {
+ std::optional<StorePath> path;
+ if (outputPaths)
+ if (auto i = outputPaths->find(outputName); i != outputPaths->end())
+ path = i->second;
+ state.mkOutputString(
+ result.alloc(outputName),
+ SingleDerivedPath::Built{
+ .drvPath = makeConstantStorePathRef(drvPath),
+ .output = outputName,
+ },
+ path);
+ }
+ v.mkAttrs(result);
+}
+
+static RegisterPrimOp primop_derivationStrictV2({
+ .name = "__derivationStrictV2",
+ .args = {"attrs"},
+ .doc = R"(
+ Create a [version 2 derivation](@docroot@/language/derivations/v2.md).
+ )",
+ .impl = prim_derivationStrictV2,
+ .experimentalFeature = Xp::DerivationsV2,
@Mic92 apologies for the negative suspense, and thank you for asking. I've gathered my thoughts, and it's multiple reasons:
The main thing that rubs me wrong is that you seem to be holding someone responsible for an experiment he did not start, but has nonetheless contributed towards anyway. I don't think that situation should affect him or unrelated parts of the project.
@Ericson2314 has been doing great work on the store layer, and unlike flakes, this is an experimental feature that nobody is urgently waiting for, so it doesn't have flakes problems of adoption during the development phase.
Experimenting with the derivation design and implementation produces insights that go towards ca-derivations and dynamic-derivations, and they improve the confidence in that feature's design.
Experiments solve a real problem, but they do not solve the flakes problem. Two different things. I wasn't expecting a knee-jerk reaction.
@@ -0,0 +1,390 @@
+#include "nix/expr/primops.hh"
+#include "nix/expr/eval-inline.hh"
+#include "nix/expr/eval-settings.hh"
+#include "nix/store/derivation/v2/convert.hh"
+#include "nix/store/downstream-placeholder.hh"
+#include "nix/store/globals.hh"
+#include "nix/store/store-api.hh"
+
+namespace nix {
+
+using namespace derivation::v2;
+
+namespace {
+
+/**
+ * Turns strings with context into interpolated strings: each store path
+ * or placeholder its context accounts for becomes a reference to the
+ * input, or own output, it stands for.
+ */
+struct Interpolator
+{
+ EvalState & state;
+ std::string_view drvName;
+ PathOf staticPathOf;
+
+ /**
+ * Keys are the strings that stand for references in the evaluator's
+ * strings: own-output placeholders, input placeholders, and the
+ * store paths of inputs.
+ */
+ std::map<std::string, Reference<SingleDerivedPath>> keys;
+
+ std::set<SingleDerivedPath> inputs;
+
+ void addOutput(const OutputName & name)
+ {
+ keys.emplace(hashPlaceholder(name), Reference<SingleDerivedPath>{name});
+ }
+
+ void addContext(const NixStringContext & context)
+ {
+ for (auto & c : context)
+ std::visit(
+ overloaded{
+ [&](const NixStringContextElem::Opaque & o) {
+ state.ensureLazyPathCopied(o.path);
+ SingleDerivedPath p = SingleDerivedPath::Opaque{.path = o.path};
+ inputs.insert(p);
+ keys.emplace(state.store->printStorePath(o.path), Reference<SingleDerivedPath>{p});
+ },
+ [&](const NixStringContextElem::Built & b) {
+ SingleDerivedPath::Built built{.drvPath = b.drvPath, .output = b.output};
+ SingleDerivedPath p = built;
+ inputs.insert(p);
+ keys.emplace(
+ DownstreamPlaceholder::fromSingleDerivedPathBuilt(built).render(),
+ Reference<SingleDerivedPath>{p});
+ if (auto path = staticPathOf(built))
+ keys.emplace(state.store->printStorePath(*path), Reference<SingleDerivedPath>{p});
+ },
+ [&](const NixStringContextElem::DrvDeep & d) {
+ /* A version 2 derivation says exactly what it depends
+ on, so there is no depending on a derivation's whole
+ closure, outputs included, in one go. */
+ state
+ .error<EvalError>(
+ "string refers to the derivation '%s' together with its whole closure, which "
+ "version 2 derivations cannot depend on; depend on the outputs needed instead, "
+ "or on the derivation alone with 'builtins.unsafeDiscardOutputDependency'",
+ state.store->printStorePath(d.drvPath))
+ .debugThrow();
+ },
+ },
+ c.raw);
+ }
+
+ Interpolated<SingleDerivedPath> interpolate(std::string_view s) const
+ {
+ Interpolated<SingleDerivedPath> res;
+ while (!s.empty()) {
+ size_t best = std::string_view::npos;
+ const std::pair<const std::string, Reference<SingleDerivedPath>> * which = nullptr;
+ for (auto & entry : keys) {
+ auto i = s.find(entry.first);
+ if (i < best || (i == best && which && entry.first.size() > which->first.size())) {
+ best = i;
+ which = &entry;
+ }
+ }
+ if (!which) {
+ res.append(std::string{s});
+ break;
+ }
+ res.append(std::string{s.substr(0, best)});
+ res.append(which->second);
+ s.remove_prefix(best + which->first.size());
+ }
+ return res;
+ }
+
+ /**
+ * Evaluate a string, and interpolate it.
+ */
+ Interpolated<SingleDerivedPath> string(Value & v, std::string_view what)
+ {
+ NixStringContext context;
+ auto s = state.coerceToString(noPos, v, context, what, false, true).toOwned();
+ addContext(context);
+ return interpolate(s);
+ }
+
+ /**
+ * Evaluate a string that must refer to exactly one thing: an own
+ * output by name, or an input by its store path or placeholder.
+ */
+ Reference<SingleDerivedPath> reference(Value & v, std::string_view what, const std::set<OutputName> & outputs)
+ {
+ NixStringContext context;
+ auto s = state.coerceToString(noPos, v, context, what, false, true).toOwned();
+ if (context.empty()) {
+ if (!outputs.contains(s))
+ state.error<EvalError>("'%s' %s is neither an output name nor a store path", s, what).debugThrow();
+ return OutputName{s};
+ }
+ addContext(context);
+ auto i = keys.find(s);
+ if (i == keys.end())
+ state.error<EvalError>("'%s' %s does not refer to exactly one input", s, what).debugThrow();
+ return i->second;
+ }
+
+ SingleDerivedPath input(Value & v, std::string_view what)
+ {
+ auto ref = reference(v, what, {});
+ auto * p = std::get_if<SingleDerivedPath>(&ref);
+ if (!p)
+ state.error<EvalError>("%s must refer to an input", what).debugThrow();
+ return *p;
+ }
+};
+
+} // namespace
+
+static StringSet forceStrings(EvalState & state, Value & v, std::string_view what)
+{
+ state.forceList(v, noPos, what);
+ StringSet res;
+ for (auto * elem : v.listView())
+ res.insert(std::string{state.forceStringNoCtx(*elem, noPos, what)});
+ return res;
+}
+
+static void prim_derivationStrictV2(EvalState & state, CallSite callSite, Value * const * args, Value & v)
+{
+
+ std::string_view errorCtx = "while evaluating the argument passed to builtins.derivationStrictV2";
+ state.forceAttrs(*args[0], noPos, errorCtx);
+ auto attrs = args[0]->attrs();
+
+ auto get = [&](std::string_view name) -> Value * {
+ auto * a = attrs->get(state.symbols.create(name));
+ return a ? a->value : nullptr;
+ };
+ auto require = [&](std::string_view name) -> Value & {
+ auto * a = get(name);
+ if (!a)
+ state.error<EvalError>("required attribute '%s' missing", name).debugThrow();
+ return *a;
+ };
+
+ Full drv{
+ .name = std::string{state.forceStringNoCtx(require("name"), noPos, "while evaluating the 'name' attribute")},
+ .platform =
+ std::string{state.forceStringNoCtx(require("system"), noPos, "while evaluating the 'system' attribute")},
+ };
+
+ try {
+ Interpolator interp{
+ .state = state,
+ .drvName = drv.name,
+ .staticPathOf = staticPathOf(*state.store),
+ };
+
+ /* The outputs first, so that the strings can refer to them. */
+ auto & outputsV = require("outputs");
+ state.forceAttrs(outputsV, noPos, "while evaluating the 'outputs' attribute");
+ std::set<OutputName> outputNames;
+ for (auto & a : *outputsV.attrs())
+ outputNames.insert(std::string{state.symbols[a.name]});
+ if (outputNames.empty())
+ state.error<EvalError>("a derivation must have at least one output").debugThrow();
+ for (auto & name : outputNames)
+ interp.addOutput(name);
+
+ drv.builder = interp.string(require("builder"), "while evaluating the 'builder' attribute");
+
+ if (auto * argsV = get("args")) {
+ state.forceList(*argsV, noPos, "while evaluating the 'args' attribute");
+ for (auto * a : argsV->listView())
+ drv.args.push_back(interp.string(*a, "while evaluating an element of the 'args' attribute"));
+ }
+
+ if (auto * envV = get("env")) {
+ state.forceAttrs(*envV, noPos, "while evaluating the 'env' attribute");
+ for (auto & a : *envV->attrs()) {
+ std::string name{state.symbols[a.name]};
+ state.forceValue(*a.value, noPos);
+ EnvVar<SingleDerivedPath> var;
+ if (a.value->type() == nAttrs) {
+ auto * valueA = a.value->attrs()->get(state.symbols.create("value"));
+ if (!valueA)
+ state.error<EvalError>("environment variable '%s' has no 'value'", name).debugThrow();
+ var.value = interp.string(*valueA->value, "while evaluating an environment variable");
+ if (auto * pf = a.value->attrs()->get(state.symbols.create("passAsFile")))
+ var.passAsFile = state.forceBool(*pf->value, noPos, "while evaluating 'passAsFile'");
+ } else {
+ var.value = interp.string(*a.value, "while evaluating an environment variable");
+ }
+ drv.env.emplace(std::move(name), std::move(var));
+ }
+ }
+
+ for (auto & a : *outputsV.attrs()) {
+ std::string outputName{state.symbols[a.name]};
+ state.forceAttrs(*a.value, noPos, "while evaluating an output");
+ auto * o = a.value->attrs();
+ auto field = [&](std::string_view f) -> Value * {
+ auto * x = o->get(state.symbols.create(f));
+ return x ? x->value : nullptr;
+ };
+
+ Output<SingleDerivedPath> output{.raw = InputAddressed{}};
+ auto * method = field("method");
+ auto * hashAlgo = field("hashAlgo");
+ if (auto * hash = field("hash")) {
+ if (!method)
+ state.error<EvalError>("output '%s' needs 'method' as well as 'hash'", outputName).debugThrow();
+ if (outputName != "out" || outputsV.attrs()->size() != 1)
+ state
+ .error<EvalError>(
+ "a derivation with a fixed content-addressed output must have just the one output 'out'")
+ .debugThrow();
+ auto m = ContentAddressMethod::parse(state.forceStringNoCtx(*method, noPos, "while evaluating 'method'"));
+ std::optional<HashAlgorithm> h;
+ if (hashAlgo)
+ h = parseHashAlgo(state.forceStringNoCtx(*hashAlgo, noPos, "while evaluating 'hashAlgo'"));
+ output.raw = derivation::Output::CAFixed{
+ .ca =
+ {
+ .method = std::move(m),
+ .hash = Hash::parseAny(state.forceStringNoCtx(*hash, noPos, "while evaluating 'hash'"), h),
+ },
+ };
+ } else if (method || hashAlgo) {
+ if (!method || !hashAlgo)
+ state.error<EvalError>("output '%s' needs both 'method' and 'hashAlgo'", outputName).debugThrow();
+ auto m = ContentAddressMethod::parse(state.forceStringNoCtx(*method, noPos, "while evaluating 'method'"));
+ auto h = parseHashAlgo(state.forceStringNoCtx(*hashAlgo, noPos, "while evaluating 'hashAlgo'"));
+ auto * impure = field("impure");
+ if (impure && state.forceBool(*impure, noPos, "while evaluating 'impure'")) {
+ experimentalFeatureSettings.require(Xp::ImpureDerivations);
+ output.raw = derivation::Output::Impure{.method = std::move(m), .hashAlgo = h};
+ } else {
+ experimentalFeatureSettings.require(Xp::CaDerivations);
+ output.raw = derivation::Output::CAFloating{.method = std::move(m), .hashAlgo = h};
+ }
+ }
+
+ if (auto * optsV = field("options")) {
+ state.forceAttrs(*optsV, noPos, "while evaluating an output's 'options'");
+ auto & c = output.options.checks;
+ auto refs = [&](Value & l, std::string_view what) {
+ state.forceList(l, noPos, what);
+ std::set<Reference<SingleDerivedPath>> res;
+ for (auto * e : l.listView())
+ res.insert(interp.reference(*e, what, outputNames));
+ return res;
+ };
+ for (auto & opt : *optsV->attrs()) {
+ std::string_view name = state.symbols[opt.name];
+ auto & ov = *opt.value;
+ if (name == "allowedReferences")
+ c.allowedReferences = refs(ov, "in 'allowedReferences'");
+ else if (name == "allowedRequisites")
+ c.allowedRequisites = refs(ov, "in 'allowedRequisites'");
+ else if (name == "disallowedReferences")
+ c.disallowedReferences = refs(ov, "in 'disallowedReferences'");
+ else if (name == "disallowedRequisites")
+ c.disallowedRequisites = refs(ov, "in 'disallowedRequisites'");
+ else if (name == "ignoreSelfRefs")
+ c.ignoreSelfRefs = state.forceBool(ov, noPos, "while evaluating 'ignoreSelfRefs'");
+ else if (name == "maxSize")
+ c.maxSize = state.forceInt(ov, noPos, "while evaluating 'maxSize'").value;
+ else if (name == "maxClosureSize")
+ c.maxClosureSize = state.forceInt(ov, noPos, "while evaluating 'maxClosureSize'").value;
+ else if (name == "unsafeDiscardReferences")
+ output.options.unsafeDiscardReferences =
+ state.forceBool(ov, noPos, "while evaluating 'unsafeDiscardReferences'");
+ else
+ state.error<EvalError>("unknown output option '%s'", name).debugThrow();
+ }
+ }
+
+ drv.outputs.emplace(std::move(outputName), std::move(output));
+ }
+
+ if (auto * optsV = get("options")) {
+ state.forceAttrs(*optsV, noPos, "while evaluating the 'options' attribute");
+ auto & o = drv.options;
+ for (auto & opt : *optsV->attrs()) {
+ std::string_view name = state.symbols[opt.name];
+ auto & ov = *opt.value;
+ auto what = fmt("while evaluating the option '%s'", name);
+ if (name == "additionalSandboxProfile")
+ o.additionalSandboxProfile = std::string{state.forceStringNoCtx(ov, noPos, what)};
+ else if (name == "allowLocalNetworking")
+ o.allowLocalNetworking = state.forceBool(ov, noPos, what);
+ else if (name == "allowSubstitutes")
+ o.allowSubstitutes = state.forceBool(ov, noPos, what);
+ else if (name == "exportReferencesGraph") {
+ state.forceAttrs(ov, noPos, what);
+ for (auto & e : *ov.attrs()) {
+ state.forceList(*e.value, noPos, what);
+ std::set<SingleDerivedPath> paths;
+ for (auto * p : e.value->listView())
+ paths.insert(interp.input(*p, "in 'exportReferencesGraph'"));
+ o.exportReferencesGraph.emplace(std::string{state.symbols[e.name]}, std::move(paths));
+ }
+ } else if (name == "impureEnvVars")
+ o.impureEnvVars = forceStrings(state, ov, what);
+ else if (name == "impureHostDeps")
+ o.impureHostDeps = forceStrings(state, ov, what);
+ else if (name == "noChroot")
+ o.noChroot = state.forceBool(ov, noPos, what);
+ else if (name == "preferLocalBuild")
+ o.preferLocalBuild = state.forceBool(ov, noPos, what);
+ else if (name == "requiredSystemFeatures")
+ o.requiredSystemFeatures = forceStrings(state, ov, what);
+ else
+ state.error<EvalError>("unknown option '%s'", name).debugThrow();
+ }
+ }
+
+ drv.inputs = derivation::FullInputs::fromSet(interp.inputs);
+ } catch (Error & e) {
+ e.addTrace(nullptr, HintFmt("while evaluating derivation '%s'", drv.name), TracePrint::Always);
+ throw;
+ }
+
+ auto drvPath = settings.readOnlyMode ? computeStorePath(*state.store, drv)
+ : writeDerivation(*state.store, drv, state.repair);
+ auto outputPaths = staticOutputPaths(*state.store, drv, staticPathOf(*state.store));
+
+ /* The derivation path refers to just the derivation, not to its
+ closure with outputs as the `drvPath` of `derivation` does. */
+ auto result = state.buildBindings(1 + drv.outputs.size());
+ result.alloc(state.s.drvPath)
+ .mkString(
+ state.store->printStorePath(drvPath),
+ {
+ NixStringContextElem::Opaque{.path = drvPath},
+ },
+ state.mem);
+ for (auto & [outputName, output] : drv.outputs) {
+ std::optional<StorePath> path;
+ if (outputPaths)
+ if (auto i = outputPaths->find(outputName); i != outputPaths->end())
+ path = i->second;
+ state.mkOutputString(
+ result.alloc(outputName),
+ SingleDerivedPath::Built{
+ .drvPath = makeConstantStorePathRef(drvPath),
+ .output = outputName,
+ },
+ path);
+ }
+ v.mkAttrs(result);
+}
+
+static RegisterPrimOp primop_derivationStrictV2({
+ .name = "__derivationStrictV2",
+ .args = {"attrs"},
+ .doc = R"(
+ Create a [version 2 derivation](@docroot@/language/derivations/v2.md).
+ )",
+ .impl = prim_derivationStrictV2,
+ .experimentalFeature = Xp::DerivationsV2,
I haven't even read this diff yet :) But my intent is that this is the "home stretch" and that I am merely combining ca and dynamic derivation features in that I don't want to bother considering them separately :)
Put another way, the actual "Worker can cope with dynamic edges" part of dynamic derivations I am already happy with, and ready to stabilize. What remains is the bureaucratic minutea of the drv format itself, and how various options and things are specialized. Which is pretty dull! But I want to get it right before stabilizing changes.
@@ -186,20 +188,6 @@ constexpr std::array<ExperimentalFeatureDetails, numXpFeatures> xpFeatureDetails
)",
.trackingUrl = "https://github.com/NixOS/nix/milestone/36",
},
- {
- .tag = Xp::DynamicDerivations,
- .name = "dynamic-derivations",
- .description = R"(
- Allow the use of a few things related to dynamic derivations:
-
- - "text hashing" derivation outputs, so we can build .drv
- files.
-
- - dependencies in derivations on the outputs of
- derivations that are themselves derivations outputs.
- )",
- .trackingUrl = "https://github.com/NixOS/nix/milestone/39",
- },
¡Hasta la vista!
@@ -0,0 +1,390 @@
+#include "nix/expr/primops.hh"
+#include "nix/expr/eval-inline.hh"
+#include "nix/expr/eval-settings.hh"
+#include "nix/store/derivation/v2/convert.hh"
+#include "nix/store/downstream-placeholder.hh"
+#include "nix/store/globals.hh"
+#include "nix/store/store-api.hh"
+
+namespace nix {
+
+using namespace derivation::v2;
+
+namespace {
+
+/**
+ * Turns strings with context into interpolated strings: each store path
+ * or placeholder its context accounts for becomes a reference to the
+ * input, or own output, it stands for.
+ */
+struct Interpolator
+{
+ EvalState & state;
+ std::string_view drvName;
+ PathOf staticPathOf;
+
+ /**
+ * Keys are the strings that stand for references in the evaluator's
+ * strings: own-output placeholders, input placeholders, and the
+ * store paths of inputs.
+ */
+ std::map<std::string, Reference<SingleDerivedPath>> keys;
+
+ std::set<SingleDerivedPath> inputs;
+
+ void addOutput(const OutputName & name)
+ {
+ keys.emplace(hashPlaceholder(name), Reference<SingleDerivedPath>{name});
+ }
+
+ void addContext(const NixStringContext & context)
+ {
+ for (auto & c : context)
+ std::visit(
+ overloaded{
+ [&](const NixStringContextElem::Opaque & o) {
+ state.ensureLazyPathCopied(o.path);
+ SingleDerivedPath p = SingleDerivedPath::Opaque{.path = o.path};
+ inputs.insert(p);
+ keys.emplace(state.store->printStorePath(o.path), Reference<SingleDerivedPath>{p});
+ },
+ [&](const NixStringContextElem::Built & b) {
+ SingleDerivedPath::Built built{.drvPath = b.drvPath, .output = b.output};
+ SingleDerivedPath p = built;
+ inputs.insert(p);
+ keys.emplace(
+ DownstreamPlaceholder::fromSingleDerivedPathBuilt(built).render(),
+ Reference<SingleDerivedPath>{p});
+ if (auto path = staticPathOf(built))
+ keys.emplace(state.store->printStorePath(*path), Reference<SingleDerivedPath>{p});
+ },
+ [&](const NixStringContextElem::DrvDeep & d) {
+ /* A version 2 derivation says exactly what it depends
+ on, so there is no depending on a derivation's whole
+ closure, outputs included, in one go. */
+ state
+ .error<EvalError>(
+ "string refers to the derivation '%s' together with its whole closure, which "
+ "version 2 derivations cannot depend on; depend on the outputs needed instead, "
+ "or on the derivation alone with 'builtins.unsafeDiscardOutputDependency'",
+ state.store->printStorePath(d.drvPath))
+ .debugThrow();
+ },
+ },
+ c.raw);
+ }
+
+ Interpolated<SingleDerivedPath> interpolate(std::string_view s) const
+ {
+ Interpolated<SingleDerivedPath> res;
+ while (!s.empty()) {
+ size_t best = std::string_view::npos;
+ const std::pair<const std::string, Reference<SingleDerivedPath>> * which = nullptr;
+ for (auto & entry : keys) {
+ auto i = s.find(entry.first);
+ if (i < best || (i == best && which && entry.first.size() > which->first.size())) {
+ best = i;
+ which = &entry;
+ }
+ }
+ if (!which) {
+ res.append(std::string{s});
+ break;
+ }
+ res.append(std::string{s.substr(0, best)});
+ res.append(which->second);
+ s.remove_prefix(best + which->first.size());
+ }
+ return res;
+ }
+
+ /**
+ * Evaluate a string, and interpolate it.
+ */
+ Interpolated<SingleDerivedPath> string(Value & v, std::string_view what)
+ {
+ NixStringContext context;
+ auto s = state.coerceToString(noPos, v, context, what, false, true).toOwned();
+ addContext(context);
+ return interpolate(s);
+ }
+
+ /**
+ * Evaluate a string that must refer to exactly one thing: an own
+ * output by name, or an input by its store path or placeholder.
+ */
+ Reference<SingleDerivedPath> reference(Value & v, std::string_view what, const std::set<OutputName> & outputs)
+ {
+ NixStringContext context;
+ auto s = state.coerceToString(noPos, v, context, what, false, true).toOwned();
+ if (context.empty()) {
+ if (!outputs.contains(s))
+ state.error<EvalError>("'%s' %s is neither an output name nor a store path", s, what).debugThrow();
+ return OutputName{s};
+ }
+ addContext(context);
+ auto i = keys.find(s);
+ if (i == keys.end())
+ state.error<EvalError>("'%s' %s does not refer to exactly one input", s, what).debugThrow();
+ return i->second;
+ }
+
+ SingleDerivedPath input(Value & v, std::string_view what)
+ {
+ auto ref = reference(v, what, {});
+ auto * p = std::get_if<SingleDerivedPath>(&ref);
+ if (!p)
+ state.error<EvalError>("%s must refer to an input", what).debugThrow();
+ return *p;
+ }
+};
+
+} // namespace
+
+static StringSet forceStrings(EvalState & state, Value & v, std::string_view what)
+{
+ state.forceList(v, noPos, what);
+ StringSet res;
+ for (auto * elem : v.listView())
+ res.insert(std::string{state.forceStringNoCtx(*elem, noPos, what)});
+ return res;
+}
+
+static void prim_derivationStrictV2(EvalState & state, CallSite callSite, Value * const * args, Value & v)
+{
+
+ std::string_view errorCtx = "while evaluating the argument passed to builtins.derivationStrictV2";
+ state.forceAttrs(*args[0], noPos, errorCtx);
+ auto attrs = args[0]->attrs();
+
+ auto get = [&](std::string_view name) -> Value * {
+ auto * a = attrs->get(state.symbols.create(name));
+ return a ? a->value : nullptr;
+ };
+ auto require = [&](std::string_view name) -> Value & {
+ auto * a = get(name);
+ if (!a)
+ state.error<EvalError>("required attribute '%s' missing", name).debugThrow();
+ return *a;
+ };
+
+ Full drv{
+ .name = std::string{state.forceStringNoCtx(require("name"), noPos, "while evaluating the 'name' attribute")},
+ .platform =
+ std::string{state.forceStringNoCtx(require("system"), noPos, "while evaluating the 'system' attribute")},
+ };
+
+ try {
+ Interpolator interp{
+ .state = state,
+ .drvName = drv.name,
+ .staticPathOf = staticPathOf(*state.store),
+ };
+
+ /* The outputs first, so that the strings can refer to them. */
+ auto & outputsV = require("outputs");
+ state.forceAttrs(outputsV, noPos, "while evaluating the 'outputs' attribute");
+ std::set<OutputName> outputNames;
+ for (auto & a : *outputsV.attrs())
+ outputNames.insert(std::string{state.symbols[a.name]});
+ if (outputNames.empty())
+ state.error<EvalError>("a derivation must have at least one output").debugThrow();
+ for (auto & name : outputNames)
+ interp.addOutput(name);
+
+ drv.builder = interp.string(require("builder"), "while evaluating the 'builder' attribute");
+
+ if (auto * argsV = get("args")) {
+ state.forceList(*argsV, noPos, "while evaluating the 'args' attribute");
+ for (auto * a : argsV->listView())
+ drv.args.push_back(interp.string(*a, "while evaluating an element of the 'args' attribute"));
+ }
+
+ if (auto * envV = get("env")) {
+ state.forceAttrs(*envV, noPos, "while evaluating the 'env' attribute");
+ for (auto & a : *envV->attrs()) {
+ std::string name{state.symbols[a.name]};
+ state.forceValue(*a.value, noPos);
+ EnvVar<SingleDerivedPath> var;
+ if (a.value->type() == nAttrs) {
+ auto * valueA = a.value->attrs()->get(state.symbols.create("value"));
+ if (!valueA)
+ state.error<EvalError>("environment variable '%s' has no 'value'", name).debugThrow();
+ var.value = interp.string(*valueA->value, "while evaluating an environment variable");
+ if (auto * pf = a.value->attrs()->get(state.symbols.create("passAsFile")))
+ var.passAsFile = state.forceBool(*pf->value, noPos, "while evaluating 'passAsFile'");
+ } else {
+ var.value = interp.string(*a.value, "while evaluating an environment variable");
+ }
+ drv.env.emplace(std::move(name), std::move(var));
+ }
+ }
+
+ for (auto & a : *outputsV.attrs()) {
+ std::string outputName{state.symbols[a.name]};
+ state.forceAttrs(*a.value, noPos, "while evaluating an output");
+ auto * o = a.value->attrs();
+ auto field = [&](std::string_view f) -> Value * {
+ auto * x = o->get(state.symbols.create(f));
+ return x ? x->value : nullptr;
+ };
+
+ Output<SingleDerivedPath> output{.raw = InputAddressed{}};
+ auto * method = field("method");
+ auto * hashAlgo = field("hashAlgo");
+ if (auto * hash = field("hash")) {
+ if (!method)
+ state.error<EvalError>("output '%s' needs 'method' as well as 'hash'", outputName).debugThrow();
+ if (outputName != "out" || outputsV.attrs()->size() != 1)
+ state
+ .error<EvalError>(
+ "a derivation with a fixed content-addressed output must have just the one output 'out'")
+ .debugThrow();
+ auto m = ContentAddressMethod::parse(state.forceStringNoCtx(*method, noPos, "while evaluating 'method'"));
+ std::optional<HashAlgorithm> h;
+ if (hashAlgo)
+ h = parseHashAlgo(state.forceStringNoCtx(*hashAlgo, noPos, "while evaluating 'hashAlgo'"));
+ output.raw = derivation::Output::CAFixed{
+ .ca =
+ {
+ .method = std::move(m),
+ .hash = Hash::parseAny(state.forceStringNoCtx(*hash, noPos, "while evaluating 'hash'"), h),
+ },
+ };
+ } else if (method || hashAlgo) {
+ if (!method || !hashAlgo)
+ state.error<EvalError>("output '%s' needs both 'method' and 'hashAlgo'", outputName).debugThrow();
+ auto m = ContentAddressMethod::parse(state.forceStringNoCtx(*method, noPos, "while evaluating 'method'"));
+ auto h = parseHashAlgo(state.forceStringNoCtx(*hashAlgo, noPos, "while evaluating 'hashAlgo'"));
+ auto * impure = field("impure");
+ if (impure && state.forceBool(*impure, noPos, "while evaluating 'impure'")) {
+ experimentalFeatureSettings.require(Xp::ImpureDerivations);
+ output.raw = derivation::Output::Impure{.method = std::move(m), .hashAlgo = h};
+ } else {
+ experimentalFeatureSettings.require(Xp::CaDerivations);
+ output.raw = derivation::Output::CAFloating{.method = std::move(m), .hashAlgo = h};
+ }
+ }
+
+ if (auto * optsV = field("options")) {
+ state.forceAttrs(*optsV, noPos, "while evaluating an output's 'options'");
+ auto & c = output.options.checks;
+ auto refs = [&](Value & l, std::string_view what) {
+ state.forceList(l, noPos, what);
+ std::set<Reference<SingleDerivedPath>> res;
+ for (auto * e : l.listView())
+ res.insert(interp.reference(*e, what, outputNames));
+ return res;
+ };
+ for (auto & opt : *optsV->attrs()) {
+ std::string_view name = state.symbols[opt.name];
+ auto & ov = *opt.value;
+ if (name == "allowedReferences")
+ c.allowedReferences = refs(ov, "in 'allowedReferences'");
+ else if (name == "allowedRequisites")
+ c.allowedRequisites = refs(ov, "in 'allowedRequisites'");
+ else if (name == "disallowedReferences")
+ c.disallowedReferences = refs(ov, "in 'disallowedReferences'");
+ else if (name == "disallowedRequisites")
+ c.disallowedRequisites = refs(ov, "in 'disallowedRequisites'");
+ else if (name == "ignoreSelfRefs")
+ c.ignoreSelfRefs = state.forceBool(ov, noPos, "while evaluating 'ignoreSelfRefs'");
+ else if (name == "maxSize")
+ c.maxSize = state.forceInt(ov, noPos, "while evaluating 'maxSize'").value;
+ else if (name == "maxClosureSize")
+ c.maxClosureSize = state.forceInt(ov, noPos, "while evaluating 'maxClosureSize'").value;
+ else if (name == "unsafeDiscardReferences")
+ output.options.unsafeDiscardReferences =
+ state.forceBool(ov, noPos, "while evaluating 'unsafeDiscardReferences'");
+ else
+ state.error<EvalError>("unknown output option '%s'", name).debugThrow();
+ }
+ }
+
+ drv.outputs.emplace(std::move(outputName), std::move(output));
+ }
+
+ if (auto * optsV = get("options")) {
+ state.forceAttrs(*optsV, noPos, "while evaluating the 'options' attribute");
+ auto & o = drv.options;
+ for (auto & opt : *optsV->attrs()) {
+ std::string_view name = state.symbols[opt.name];
+ auto & ov = *opt.value;
+ auto what = fmt("while evaluating the option '%s'", name);
+ if (name == "additionalSandboxProfile")
+ o.additionalSandboxProfile = std::string{state.forceStringNoCtx(ov, noPos, what)};
+ else if (name == "allowLocalNetworking")
+ o.allowLocalNetworking = state.forceBool(ov, noPos, what);
+ else if (name == "allowSubstitutes")
+ o.allowSubstitutes = state.forceBool(ov, noPos, what);
+ else if (name == "exportReferencesGraph") {
+ state.forceAttrs(ov, noPos, what);
+ for (auto & e : *ov.attrs()) {
+ state.forceList(*e.value, noPos, what);
+ std::set<SingleDerivedPath> paths;
+ for (auto * p : e.value->listView())
+ paths.insert(interp.input(*p, "in 'exportReferencesGraph'"));
+ o.exportReferencesGraph.emplace(std::string{state.symbols[e.name]}, std::move(paths));
+ }
+ } else if (name == "impureEnvVars")
+ o.impureEnvVars = forceStrings(state, ov, what);
+ else if (name == "impureHostDeps")
+ o.impureHostDeps = forceStrings(state, ov, what);
+ else if (name == "noChroot")
+ o.noChroot = state.forceBool(ov, noPos, what);
+ else if (name == "preferLocalBuild")
+ o.preferLocalBuild = state.forceBool(ov, noPos, what);
+ else if (name == "requiredSystemFeatures")
+ o.requiredSystemFeatures = forceStrings(state, ov, what);
+ else
+ state.error<EvalError>("unknown option '%s'", name).debugThrow();
+ }
+ }
+
+ drv.inputs = derivation::FullInputs::fromSet(interp.inputs);
+ } catch (Error & e) {
+ e.addTrace(nullptr, HintFmt("while evaluating derivation '%s'", drv.name), TracePrint::Always);
+ throw;
+ }
+
+ auto drvPath = settings.readOnlyMode ? computeStorePath(*state.store, drv)
+ : writeDerivation(*state.store, drv, state.repair);
+ auto outputPaths = staticOutputPaths(*state.store, drv, staticPathOf(*state.store));
+
+ /* The derivation path refers to just the derivation, not to its
+ closure with outputs as the `drvPath` of `derivation` does. */
+ auto result = state.buildBindings(1 + drv.outputs.size());
+ result.alloc(state.s.drvPath)
+ .mkString(
+ state.store->printStorePath(drvPath),
+ {
+ NixStringContextElem::Opaque{.path = drvPath},
+ },
+ state.mem);
+ for (auto & [outputName, output] : drv.outputs) {
+ std::optional<StorePath> path;
+ if (outputPaths)
+ if (auto i = outputPaths->find(outputName); i != outputPaths->end())
+ path = i->second;
+ state.mkOutputString(
+ result.alloc(outputName),
+ SingleDerivedPath::Built{
+ .drvPath = makeConstantStorePathRef(drvPath),
+ .output = outputName,
+ },
+ path);
+ }
+ v.mkAttrs(result);
+}
+
+static RegisterPrimOp primop_derivationStrictV2({
+ .name = "__derivationStrictV2",
+ .args = {"attrs"},
+ .doc = R"(
+ Create a [version 2 derivation](@docroot@/language/derivations/v2.md).
+ )",
+ .impl = prim_derivationStrictV2,
+ .experimentalFeature = Xp::DerivationsV2,
I don't know maybe I am just feeling a bit crumpy that @Ericson2314 like to jump onto the next shiny feature/refactoring while I feeling ignored on load-bearing patches like https://github.com/NixOS/nix/pull/16477 that make "experimental" features like ca-derivation somewhat usable if you actually use them outside of the nix testsuite for more than a day.
Ericson2314
Residual = Change × (1 − Confidence)
Mic92
A lot of things :), see the manual changes.
---
Add :+1: to pull requests you find important.
The Nix maintainer team uses a GitHub project board to schedule and track reviews.