aboutsummaryrefslogtreecommitdiff
path: root/src/libexpr
diff options
context:
space:
mode:
Diffstat (limited to 'src/libexpr')
-rw-r--r--src/libexpr/attr-path.cc22
-rw-r--r--src/libexpr/attr-path.hh4
-rw-r--r--src/libexpr/attr-set.cc6
-rw-r--r--src/libexpr/attr-set.hh50
-rw-r--r--src/libexpr/common-eval-args.cc101
-rw-r--r--src/libexpr/common-eval-args.hh27
-rw-r--r--src/libexpr/eval-cache.cc237
-rw-r--r--src/libexpr/eval-cache.hh25
-rw-r--r--src/libexpr/eval-inline.hh103
-rw-r--r--src/libexpr/eval.cc757
-rw-r--r--src/libexpr/eval.hh262
-rw-r--r--src/libexpr/fetchurl.nix8
-rw-r--r--src/libexpr/flake/call-flake.nix2
-rw-r--r--src/libexpr/flake/config.cc16
-rw-r--r--src/libexpr/flake/flake.cc163
-rw-r--r--src/libexpr/flake/flakeref.cc23
-rw-r--r--src/libexpr/flake/flakeref.hh10
-rw-r--r--src/libexpr/flake/lockfile.cc2
-rw-r--r--src/libexpr/function-trace.hh2
-rw-r--r--src/libexpr/get-drvs.cc119
-rw-r--r--src/libexpr/get-drvs.hh23
-rw-r--r--src/libexpr/lexer.l25
-rw-r--r--src/libexpr/nixexpr.cc384
-rw-r--r--src/libexpr/nixexpr.hh237
-rw-r--r--src/libexpr/parser.y124
-rw-r--r--src/libexpr/primops.cc825
-rw-r--r--src/libexpr/primops.hh6
-rw-r--r--src/libexpr/primops/context.cc52
-rw-r--r--src/libexpr/primops/fetchClosure.cc163
-rw-r--r--src/libexpr/primops/fetchMercurial.cc16
-rw-r--r--src/libexpr/primops/fetchTree.cc104
-rw-r--r--src/libexpr/primops/fromTOML.cc4
-rw-r--r--src/libexpr/symbol-table.hh97
-rw-r--r--src/libexpr/tests/json.cc68
-rw-r--r--src/libexpr/tests/libexprtests.hh136
-rw-r--r--src/libexpr/tests/local.mk15
-rw-r--r--src/libexpr/tests/primops.cc839
-rw-r--r--src/libexpr/tests/trivial.cc196
-rw-r--r--src/libexpr/value-to-json.cc31
-rw-r--r--src/libexpr/value-to-json.hh4
-rw-r--r--src/libexpr/value-to-xml.cc30
-rw-r--r--src/libexpr/value-to-xml.hh2
-rw-r--r--src/libexpr/value.hh31
43 files changed, 3855 insertions, 1496 deletions
diff --git a/src/libexpr/attr-path.cc b/src/libexpr/attr-path.cc
index eb0e706c7..94ab60f9a 100644
--- a/src/libexpr/attr-path.cc
+++ b/src/libexpr/attr-path.cc
@@ -41,13 +41,13 @@ std::vector<Symbol> parseAttrPath(EvalState & state, std::string_view s)
}
-std::pair<Value *, Pos> findAlongAttrPath(EvalState & state, const std::string & attrPath,
+std::pair<Value *, PosIdx> findAlongAttrPath(EvalState & state, const std::string & attrPath,
Bindings & autoArgs, Value & vIn)
{
Strings tokens = parseAttrPath(attrPath);
Value * v = &vIn;
- Pos pos = noPos;
+ PosIdx pos = noPos;
for (auto & attr : tokens) {
@@ -74,10 +74,16 @@ std::pair<Value *, Pos> findAlongAttrPath(EvalState & state, const std::string &
throw Error("empty attribute name in selection path '%1%'", attrPath);
Bindings::iterator a = v->attrs->find(state.symbols.create(attr));
- if (a == v->attrs->end())
- throw AttrPathNotFound("attribute '%1%' in selection path '%2%' not found", attr, attrPath);
+ if (a == v->attrs->end()) {
+ std::set<std::string> attrNames;
+ for (auto & attr : *v->attrs)
+ attrNames.insert(state.symbols[attr.name]);
+
+ auto suggestions = Suggestions::bestMatches(attrNames, attr);
+ throw AttrPathNotFound(suggestions, "attribute '%1%' in selection path '%2%' not found", attr, attrPath);
+ }
v = &*a->value;
- pos = *a->pos;
+ pos = a->pos;
}
else {
@@ -100,7 +106,7 @@ std::pair<Value *, Pos> findAlongAttrPath(EvalState & state, const std::string &
}
-Pos findPackageFilename(EvalState & state, Value & v, std::string what)
+std::pair<std::string, uint32_t> findPackageFilename(EvalState & state, Value & v, std::string what)
{
Value * v2;
try {
@@ -126,9 +132,7 @@ Pos findPackageFilename(EvalState & state, Value & v, std::string what)
throw ParseError("cannot parse line number '%s'", pos);
}
- Symbol file = state.symbols.create(filename);
-
- return { foFile, file, lineno, 0 };
+ return { std::move(filename), lineno };
}
diff --git a/src/libexpr/attr-path.hh b/src/libexpr/attr-path.hh
index ff1135a06..117e0051b 100644
--- a/src/libexpr/attr-path.hh
+++ b/src/libexpr/attr-path.hh
@@ -10,14 +10,14 @@ namespace nix {
MakeError(AttrPathNotFound, Error);
MakeError(NoPositionInfo, Error);
-std::pair<Value *, Pos> findAlongAttrPath(
+std::pair<Value *, PosIdx> findAlongAttrPath(
EvalState & state,
const std::string & attrPath,
Bindings & autoArgs,
Value & vIn);
/* Heuristic to find the filename and lineno or a nix value. */
-Pos findPackageFilename(EvalState & state, Value & v, std::string what);
+std::pair<std::string, uint32_t> findPackageFilename(EvalState & state, Value & v, std::string what);
std::vector<Symbol> parseAttrPath(EvalState & state, std::string_view s);
diff --git a/src/libexpr/attr-set.cc b/src/libexpr/attr-set.cc
index 52ac47e9b..877116f1f 100644
--- a/src/libexpr/attr-set.cc
+++ b/src/libexpr/attr-set.cc
@@ -26,7 +26,7 @@ Bindings * EvalState::allocBindings(size_t capacity)
/* Create a new attribute named 'name' on an existing attribute set stored
in 'vAttrs' and return the newly allocated Value which is associated with
this attribute. */
-Value * EvalState::allocAttr(Value & vAttrs, const Symbol & name)
+Value * EvalState::allocAttr(Value & vAttrs, Symbol name)
{
Value * v = allocValue();
vAttrs.attrs->push_back(Attr(name, v));
@@ -40,7 +40,7 @@ Value * EvalState::allocAttr(Value & vAttrs, std::string_view name)
}
-Value & BindingsBuilder::alloc(const Symbol & name, ptr<Pos> pos)
+Value & BindingsBuilder::alloc(Symbol name, PosIdx pos)
{
auto value = state.allocValue();
bindings->push_back(Attr(name, value, pos));
@@ -48,7 +48,7 @@ Value & BindingsBuilder::alloc(const Symbol & name, ptr<Pos> pos)
}
-Value & BindingsBuilder::alloc(std::string_view name, ptr<Pos> pos)
+Value & BindingsBuilder::alloc(std::string_view name, PosIdx pos)
{
return alloc(state.symbols.create(name), pos);
}
diff --git a/src/libexpr/attr-set.hh b/src/libexpr/attr-set.hh
index cad9743ea..dcc73b506 100644
--- a/src/libexpr/attr-set.hh
+++ b/src/libexpr/attr-set.hh
@@ -15,18 +15,27 @@ struct Value;
/* Map one attribute name to its value. */
struct Attr
{
+ /* the placement of `name` and `pos` in this struct is important.
+ both of them are uint32 wrappers, they are next to each other
+ to make sure that Attr has no padding on 64 bit machines. that
+ way we keep Attr size at two words with no wasted space. */
Symbol name;
+ PosIdx pos;
Value * value;
- ptr<Pos> pos;
- Attr(Symbol name, Value * value, ptr<Pos> pos = ptr(&noPos))
- : name(name), value(value), pos(pos) { };
- Attr() : pos(&noPos) { };
+ Attr(Symbol name, Value * value, PosIdx pos = noPos)
+ : name(name), pos(pos), value(value) { };
+ Attr() { };
bool operator < (const Attr & a) const
{
return name < a.name;
}
};
+static_assert(sizeof(Attr) == 2 * sizeof(uint32_t) + sizeof(Value *),
+ "performance of the evaluator is highly sensitive to the size of Attr. "
+ "avoid introducing any padding into Attr if at all possible, and do not "
+ "introduce new fields that need not be present for almost every instance.");
+
/* Bindings contains all the attributes of an attribute set. It is defined
by its size and its capacity, the capacity being the number of Attr
elements allocated after this structure, while the size corresponds to
@@ -35,13 +44,13 @@ class Bindings
{
public:
typedef uint32_t size_t;
- ptr<Pos> pos;
+ PosIdx pos;
private:
size_t size_, capacity_;
Attr attrs[0];
- Bindings(size_t capacity) : pos(&noPos), size_(0), capacity_(capacity) { }
+ Bindings(size_t capacity) : size_(0), capacity_(capacity) { }
Bindings(const Bindings & bindings) = delete;
public:
@@ -57,7 +66,7 @@ public:
attrs[size_++] = attr;
}
- iterator find(const Symbol & name)
+ iterator find(Symbol name)
{
Attr key(name, 0);
iterator i = std::lower_bound(begin(), end(), key);
@@ -65,7 +74,7 @@ public:
return end();
}
- Attr * get(const Symbol & name)
+ Attr * get(Symbol name)
{
Attr key(name, 0);
iterator i = std::lower_bound(begin(), end(), key);
@@ -73,18 +82,6 @@ public:
return nullptr;
}
- Attr & need(const Symbol & name, const Pos & pos = noPos)
- {
- auto a = get(name);
- if (!a)
- throw Error({
- .msg = hintfmt("attribute '%s' missing", name),
- .errPos = pos
- });
-
- return *a;
- }
-
iterator begin() { return &attrs[0]; }
iterator end() { return &attrs[size_]; }
@@ -98,14 +95,15 @@ public:
size_t capacity() { return capacity_; }
/* Returns the attributes in lexicographically sorted order. */
- std::vector<const Attr *> lexicographicOrder() const
+ std::vector<const Attr *> lexicographicOrder(const SymbolTable & symbols) const
{
std::vector<const Attr *> res;
res.reserve(size_);
for (size_t n = 0; n < size_; n++)
res.emplace_back(&attrs[n]);
- std::sort(res.begin(), res.end(), [](const Attr * a, const Attr * b) {
- return (const std::string &) a->name < (const std::string &) b->name;
+ std::sort(res.begin(), res.end(), [&](const Attr * a, const Attr * b) {
+ std::string_view sa = symbols[a->name], sb = symbols[b->name];
+ return sa < sb;
});
return res;
}
@@ -130,7 +128,7 @@ public:
: bindings(bindings), state(state)
{ }
- void insert(Symbol name, Value * value, ptr<Pos> pos = ptr(&noPos))
+ void insert(Symbol name, Value * value, PosIdx pos = noPos)
{
insert(Attr(name, value, pos));
}
@@ -145,9 +143,9 @@ public:
bindings->push_back(attr);
}
- Value & alloc(const Symbol & name, ptr<Pos> pos = ptr(&noPos));
+ Value & alloc(Symbol name, PosIdx pos = noPos);
- Value & alloc(std::string_view name, ptr<Pos> pos = ptr(&noPos));
+ Value & alloc(std::string_view name, PosIdx pos = noPos);
Bindings * finish()
{
diff --git a/src/libexpr/common-eval-args.cc b/src/libexpr/common-eval-args.cc
deleted file mode 100644
index e50ff244c..000000000
--- a/src/libexpr/common-eval-args.cc
+++ /dev/null
@@ -1,101 +0,0 @@
-#include "common-eval-args.hh"
-#include "shared.hh"
-#include "filetransfer.hh"
-#include "util.hh"
-#include "eval.hh"
-#include "fetchers.hh"
-#include "registry.hh"
-#include "flake/flakeref.hh"
-#include "store-api.hh"
-
-namespace nix {
-
-MixEvalArgs::MixEvalArgs()
-{
- auto category = "Common evaluation options";
-
- addFlag({
- .longName = "arg",
- .description = "Pass the value *expr* as the argument *name* to Nix functions.",
- .category = category,
- .labels = {"name", "expr"},
- .handler = {[&](std::string name, std::string expr) { autoArgs[name] = 'E' + expr; }}
- });
-
- addFlag({
- .longName = "argstr",
- .description = "Pass the string *string* as the argument *name* to Nix functions.",
- .category = category,
- .labels = {"name", "string"},
- .handler = {[&](std::string name, std::string s) { autoArgs[name] = 'S' + s; }},
- });
-
- addFlag({
- .longName = "include",
- .shortName = 'I',
- .description = "Add *path* to the list of locations used to look up `<...>` file names.",
- .category = category,
- .labels = {"path"},
- .handler = {[&](std::string s) { searchPath.push_back(s); }}
- });
-
- addFlag({
- .longName = "impure",
- .description = "Allow access to mutable paths and repositories.",
- .category = category,
- .handler = {[&]() {
- evalSettings.pureEval = false;
- }},
- });
-
- addFlag({
- .longName = "override-flake",
- .description = "Override the flake registries, redirecting *original-ref* to *resolved-ref*.",
- .category = category,
- .labels = {"original-ref", "resolved-ref"},
- .handler = {[&](std::string _from, std::string _to) {
- auto from = parseFlakeRef(_from, absPath("."));
- auto to = parseFlakeRef(_to, absPath("."));
- fetchers::Attrs extraAttrs;
- if (to.subdir != "") extraAttrs["dir"] = to.subdir;
- fetchers::overrideRegistry(from.input, to.input, extraAttrs);
- }}
- });
-
- addFlag({
- .longName = "eval-store",
- .description = "The Nix store to use for evaluations.",
- .category = category,
- .labels = {"store-url"},
- .handler = {&evalStoreUrl},
- });
-}
-
-Bindings * MixEvalArgs::getAutoArgs(EvalState & state)
-{
- auto res = state.buildBindings(autoArgs.size());
- for (auto & i : autoArgs) {
- auto v = state.allocValue();
- if (i.second[0] == 'E')
- state.mkThunk_(*v, state.parseExprFromString(i.second.substr(1), absPath(".")));
- else
- v->mkString(((std::string_view) i.second).substr(1));
- res.insert(state.symbols.create(i.first), v);
- }
- return res.finish();
-}
-
-Path lookupFileArg(EvalState & state, std::string_view s)
-{
- if (isUri(s)) {
- return state.store->toRealPath(
- fetchers::downloadTarball(
- state.store, resolveUri(s), "source", false).first.storePath);
- } else if (s.size() > 2 && s.at(0) == '<' && s.at(s.size() - 1) == '>') {
- Path p(s.substr(1, s.size() - 2));
- return state.findFile(p);
- } else
- return absPath(std::string(s));
-}
-
-}
diff --git a/src/libexpr/common-eval-args.hh b/src/libexpr/common-eval-args.hh
deleted file mode 100644
index 03fa226aa..000000000
--- a/src/libexpr/common-eval-args.hh
+++ /dev/null
@@ -1,27 +0,0 @@
-#pragma once
-
-#include "args.hh"
-
-namespace nix {
-
-class Store;
-class EvalState;
-class Bindings;
-
-struct MixEvalArgs : virtual Args
-{
- MixEvalArgs();
-
- Bindings * getAutoArgs(EvalState & state);
-
- Strings searchPath;
-
- std::optional<std::string> evalStoreUrl;
-
-private:
- std::map<std::string, std::string> autoArgs;
-};
-
-Path lookupFileArg(EvalState & state, std::string_view s);
-
-}
diff --git a/src/libexpr/eval-cache.cc b/src/libexpr/eval-cache.cc
index 00d0749f9..b259eec63 100644
--- a/src/libexpr/eval-cache.cc
+++ b/src/libexpr/eval-cache.cc
@@ -21,6 +21,8 @@ struct AttrDb
{
std::atomic_bool failed{false};
+ const Store & cfg;
+
struct State
{
SQLite db;
@@ -33,12 +35,19 @@ struct AttrDb
std::unique_ptr<Sync<State>> _state;
- AttrDb(const Hash & fingerprint)
- : _state(std::make_unique<Sync<State>>())
+ SymbolTable & symbols;
+
+ AttrDb(
+ const Store & cfg,
+ const Hash & fingerprint,
+ SymbolTable & symbols)
+ : cfg(cfg)
+ , _state(std::make_unique<Sync<State>>())
+ , symbols(symbols)
{
auto state(_state->lock());
- Path cacheDir = getCacheDir() + "/nix/eval-cache-v2";
+ Path cacheDir = getCacheDir() + "/nix/eval-cache-v4";
createDirs(cacheDir);
Path dbPath = cacheDir + "/" + fingerprint.to_string(Base16, false) + ".sqlite";
@@ -97,7 +106,7 @@ struct AttrDb
state->insertAttribute.use()
(key.first)
- (key.second)
+ (symbols[key.second])
(AttrType::FullAttrs)
(0, false).exec();
@@ -107,7 +116,7 @@ struct AttrDb
for (auto & attr : attrs)
state->insertAttribute.use()
(rowId)
- (attr)
+ (symbols[attr])
(AttrType::Placeholder)
(0, false).exec();
@@ -132,14 +141,14 @@ struct AttrDb
}
state->insertAttributeWithContext.use()
(key.first)
- (key.second)
+ (symbols[key.second])
(AttrType::String)
(s)
(ctx).exec();
} else {
state->insertAttribute.use()
(key.first)
- (key.second)
+ (symbols[key.second])
(AttrType::String)
(s).exec();
}
@@ -158,7 +167,7 @@ struct AttrDb
state->insertAttribute.use()
(key.first)
- (key.second)
+ (symbols[key.second])
(AttrType::Bool)
(b ? 1 : 0).exec();
@@ -166,6 +175,42 @@ struct AttrDb
});
}
+ AttrId setInt(
+ AttrKey key,
+ int n)
+ {
+ return doSQLite([&]()
+ {
+ auto state(_state->lock());
+
+ state->insertAttribute.use()
+ (key.first)
+ (symbols[key.second])
+ (AttrType::Int)
+ (n).exec();
+
+ return state->db.getLastInsertedRowId();
+ });
+ }
+
+ AttrId setListOfStrings(
+ AttrKey key,
+ const std::vector<std::string> & l)
+ {
+ return doSQLite([&]()
+ {
+ auto state(_state->lock());
+
+ state->insertAttribute.use()
+ (key.first)
+ (symbols[key.second])
+ (AttrType::ListOfStrings)
+ (concatStringsSep("\t", l)).exec();
+
+ return state->db.getLastInsertedRowId();
+ });
+ }
+
AttrId setPlaceholder(AttrKey key)
{
return doSQLite([&]()
@@ -174,7 +219,7 @@ struct AttrDb
state->insertAttribute.use()
(key.first)
- (key.second)
+ (symbols[key.second])
(AttrType::Placeholder)
(0, false).exec();
@@ -190,7 +235,7 @@ struct AttrDb
state->insertAttribute.use()
(key.first)
- (key.second)
+ (symbols[key.second])
(AttrType::Missing)
(0, false).exec();
@@ -206,7 +251,7 @@ struct AttrDb
state->insertAttribute.use()
(key.first)
- (key.second)
+ (symbols[key.second])
(AttrType::Misc)
(0, false).exec();
@@ -222,7 +267,7 @@ struct AttrDb
state->insertAttribute.use()
(key.first)
- (key.second)
+ (symbols[key.second])
(AttrType::Failed)
(0, false).exec();
@@ -230,16 +275,14 @@ struct AttrDb
});
}
- std::optional<std::pair<AttrId, AttrValue>> getAttr(
- AttrKey key,
- SymbolTable & symbols)
+ std::optional<std::pair<AttrId, AttrValue>> getAttr(AttrKey key)
{
auto state(_state->lock());
- auto queryAttribute(state->queryAttribute.use()(key.first)(key.second));
+ auto queryAttribute(state->queryAttribute.use()(key.first)(symbols[key.second]));
if (!queryAttribute.next()) return {};
- auto rowId = (AttrType) queryAttribute.getInt(0);
+ auto rowId = (AttrId) queryAttribute.getInt(0);
auto type = (AttrType) queryAttribute.getInt(1);
switch (type) {
@@ -250,18 +293,22 @@ struct AttrDb
std::vector<Symbol> attrs;
auto queryAttributes(state->queryAttributes.use()(rowId));
while (queryAttributes.next())
- attrs.push_back(symbols.create(queryAttributes.getStr(0)));
+ attrs.emplace_back(symbols.create(queryAttributes.getStr(0)));
return {{rowId, attrs}};
}
case AttrType::String: {
- std::vector<std::pair<Path, std::string>> context;
+ NixStringContext context;
if (!queryAttribute.isNull(3))
for (auto & s : tokenizeString<std::vector<std::string>>(queryAttribute.getStr(3), ";"))
- context.push_back(decodeContext(s));
+ context.push_back(decodeContext(cfg, s));
return {{rowId, string_t{queryAttribute.getStr(2), context}}};
}
case AttrType::Bool:
return {{rowId, queryAttribute.getInt(2) != 0}};
+ case AttrType::Int:
+ return {{rowId, int_t{queryAttribute.getInt(2)}}};
+ case AttrType::ListOfStrings:
+ return {{rowId, tokenizeString<std::vector<std::string>>(queryAttribute.getStr(2), "\t")}};
case AttrType::Missing:
return {{rowId, missing_t()}};
case AttrType::Misc:
@@ -274,10 +321,13 @@ struct AttrDb
}
};
-static std::shared_ptr<AttrDb> makeAttrDb(const Hash & fingerprint)
+static std::shared_ptr<AttrDb> makeAttrDb(
+ const Store & cfg,
+ const Hash & fingerprint,
+ SymbolTable & symbols)
{
try {
- return std::make_shared<AttrDb>(fingerprint);
+ return std::make_shared<AttrDb>(cfg, fingerprint, symbols);
} catch (SQLiteError &) {
ignoreException();
return nullptr;
@@ -288,7 +338,7 @@ EvalCache::EvalCache(
std::optional<std::reference_wrapper<const Hash>> useCache,
EvalState & state,
RootLoader rootLoader)
- : db(useCache ? makeAttrDb(*useCache) : nullptr)
+ : db(useCache ? makeAttrDb(*state.store, *useCache, state.symbols) : nullptr)
, state(state)
, rootLoader(rootLoader)
{
@@ -303,9 +353,9 @@ Value * EvalCache::getRootValue()
return *value;
}
-std::shared_ptr<AttrCursor> EvalCache::getRoot()
+ref<AttrCursor> EvalCache::getRoot()
{
- return std::make_shared<AttrCursor>(ref(shared_from_this()), std::nullopt);
+ return make_ref<AttrCursor>(ref(shared_from_this()), std::nullopt);
}
AttrCursor::AttrCursor(
@@ -324,8 +374,7 @@ AttrKey AttrCursor::getKey()
if (!parent)
return {0, root->state.sEpsilon};
if (!parent->first->cachedValue) {
- parent->first->cachedValue = root->db->getAttr(
- parent->first->getKey(), root->state.symbols);
+ parent->first->cachedValue = root->db->getAttr(parent->first->getKey());
assert(parent->first->cachedValue);
}
return {parent->first->cachedValue->first, parent->second};
@@ -366,17 +415,17 @@ std::vector<Symbol> AttrCursor::getAttrPath(Symbol name) const
std::string AttrCursor::getAttrPathStr() const
{
- return concatStringsSep(".", getAttrPath());
+ return concatStringsSep(".", root->state.symbols.resolve(getAttrPath()));
}
std::string AttrCursor::getAttrPathStr(Symbol name) const
{
- return concatStringsSep(".", getAttrPath(name));
+ return concatStringsSep(".", root->state.symbols.resolve(getAttrPath(name)));
}
Value & AttrCursor::forceValue()
{
- debug("evaluating uncached attribute %s", getAttrPathStr());
+ debug("evaluating uncached attribute '%s'", getAttrPathStr());
auto & v = getValue();
@@ -397,6 +446,8 @@ Value & AttrCursor::forceValue()
cachedValue = {root->db->setString(getKey(), v.path), string_t{v.path, {}}};
else if (v.type() == nBool)
cachedValue = {root->db->setBool(getKey(), v.boolean), v.boolean};
+ else if (v.type() == nInt)
+ cachedValue = {root->db->setInt(getKey(), v.integer), int_t{v.integer}};
else if (v.type() == nAttrs)
; // FIXME: do something?
else
@@ -406,26 +457,36 @@ Value & AttrCursor::forceValue()
return v;
}
+Suggestions AttrCursor::getSuggestionsForAttr(Symbol name)
+{
+ auto attrNames = getAttrs();
+ std::set<std::string> strAttrNames;
+ for (auto & name : attrNames)
+ strAttrNames.insert(root->state.symbols[name]);
+
+ return Suggestions::bestMatches(strAttrNames, root->state.symbols[name]);
+}
+
std::shared_ptr<AttrCursor> AttrCursor::maybeGetAttr(Symbol name, bool forceErrors)
{
if (root->db) {
if (!cachedValue)
- cachedValue = root->db->getAttr(getKey(), root->state.symbols);
+ cachedValue = root->db->getAttr(getKey());
if (cachedValue) {
if (auto attrs = std::get_if<std::vector<Symbol>>(&cachedValue->second)) {
for (auto & attr : *attrs)
if (attr == name)
- return std::make_shared<AttrCursor>(root, std::make_pair(shared_from_this(), name));
+ return std::make_shared<AttrCursor>(root, std::make_pair(shared_from_this(), attr));
return nullptr;
} else if (std::get_if<placeholder_t>(&cachedValue->second)) {
- auto attr = root->db->getAttr({cachedValue->first, name}, root->state.symbols);
+ auto attr = root->db->getAttr({cachedValue->first, name});
if (attr) {
if (std::get_if<missing_t>(&attr->second))
return nullptr;
else if (std::get_if<failed_t>(&attr->second)) {
if (forceErrors)
- debug("reevaluating failed cached attribute '%s'");
+ debug("reevaluating failed cached attribute '%s'", getAttrPathStr(name));
else
throw CachedEvalError("cached failure of attribute '%s'", getAttrPathStr(name));
} else
@@ -464,7 +525,7 @@ std::shared_ptr<AttrCursor> AttrCursor::maybeGetAttr(Symbol name, bool forceErro
cachedValue2 = {root->db->setPlaceholder({cachedValue->first, name}), placeholder_t()};
}
- return std::make_shared<AttrCursor>(
+ return make_ref<AttrCursor>(
root, std::make_pair(shared_from_this(), name), attr->value, std::move(cachedValue2));
}
@@ -473,47 +534,51 @@ std::shared_ptr<AttrCursor> AttrCursor::maybeGetAttr(std::string_view name)
return maybeGetAttr(root->state.symbols.create(name));
}
-std::shared_ptr<AttrCursor> AttrCursor::getAttr(Symbol name, bool forceErrors)
+ref<AttrCursor> AttrCursor::getAttr(Symbol name, bool forceErrors)
{
auto p = maybeGetAttr(name, forceErrors);
if (!p)
throw Error("attribute '%s' does not exist", getAttrPathStr(name));
- return p;
+ return ref(p);
}
-std::shared_ptr<AttrCursor> AttrCursor::getAttr(std::string_view name)
+ref<AttrCursor> AttrCursor::getAttr(std::string_view name)
{
return getAttr(root->state.symbols.create(name));
}
-std::shared_ptr<AttrCursor> AttrCursor::findAlongAttrPath(const std::vector<Symbol> & attrPath, bool force)
+OrSuggestions<ref<AttrCursor>> AttrCursor::findAlongAttrPath(const std::vector<Symbol> & attrPath, bool force)
{
auto res = shared_from_this();
for (auto & attr : attrPath) {
- res = res->maybeGetAttr(attr, force);
- if (!res) return {};
+ auto child = res->maybeGetAttr(attr, force);
+ if (!child) {
+ auto suggestions = res->getSuggestionsForAttr(attr);
+ return OrSuggestions<ref<AttrCursor>>::failed(suggestions);
+ }
+ res = child;
}
- return res;
+ return ref(res);
}
std::string AttrCursor::getString()
{
if (root->db) {
if (!cachedValue)
- cachedValue = root->db->getAttr(getKey(), root->state.symbols);
+ cachedValue = root->db->getAttr(getKey());
if (cachedValue && !std::get_if<placeholder_t>(&cachedValue->second)) {
if (auto s = std::get_if<string_t>(&cachedValue->second)) {
debug("using cached string attribute '%s'", getAttrPathStr());
return s->first;
} else
- throw TypeError("'%s' is not a string", getAttrPathStr());
+ root->state.debugThrowLastTrace(TypeError("'%s' is not a string", getAttrPathStr()));
}
}
auto & v = forceValue();
if (v.type() != nString && v.type() != nPath)
- throw TypeError("'%s' is not a string but %s", getAttrPathStr(), showType(v.type()));
+ root->state.debugThrowLastTrace(TypeError("'%s' is not a string but %s", getAttrPathStr(), showType(v.type())));
return v.type() == nString ? v.string.s : v.path;
}
@@ -522,12 +587,12 @@ string_t AttrCursor::getStringWithContext()
{
if (root->db) {
if (!cachedValue)
- cachedValue = root->db->getAttr(getKey(), root->state.symbols);
+ cachedValue = root->db->getAttr(getKey());
if (cachedValue && !std::get_if<placeholder_t>(&cachedValue->second)) {
if (auto s = std::get_if<string_t>(&cachedValue->second)) {
bool valid = true;
for (auto & c : s->second) {
- if (!root->state.store->isValidPath(root->state.store->parseStorePath(c.first))) {
+ if (!root->state.store->isValidPath(c.first)) {
valid = false;
break;
}
@@ -537,66 +602,122 @@ string_t AttrCursor::getStringWithContext()
return *s;
}
} else
- throw TypeError("'%s' is not a string", getAttrPathStr());
+ root->state.debugThrowLastTrace(TypeError("'%s' is not a string", getAttrPathStr()));
}
}
auto & v = forceValue();
if (v.type() == nString)
- return {v.string.s, v.getContext()};
+ return {v.string.s, v.getContext(*root->state.store)};
else if (v.type() == nPath)
return {v.path, {}};
else
- throw TypeError("'%s' is not a string but %s", getAttrPathStr(), showType(v.type()));
+ root->state.debugThrowLastTrace(TypeError("'%s' is not a string but %s", getAttrPathStr(), showType(v.type())));
}
bool AttrCursor::getBool()
{
if (root->db) {
if (!cachedValue)
- cachedValue = root->db->getAttr(getKey(), root->state.symbols);
+ cachedValue = root->db->getAttr(getKey());
if (cachedValue && !std::get_if<placeholder_t>(&cachedValue->second)) {
if (auto b = std::get_if<bool>(&cachedValue->second)) {
debug("using cached Boolean attribute '%s'", getAttrPathStr());
return *b;
} else
- throw TypeError("'%s' is not a Boolean", getAttrPathStr());
+ root->state.debugThrowLastTrace(TypeError("'%s' is not a Boolean", getAttrPathStr()));
}
}
auto & v = forceValue();
if (v.type() != nBool)
- throw TypeError("'%s' is not a Boolean", getAttrPathStr());
+ root->state.debugThrowLastTrace(TypeError("'%s' is not a Boolean", getAttrPathStr()));
return v.boolean;
}
+NixInt AttrCursor::getInt()
+{
+ if (root->db) {
+ if (!cachedValue)
+ cachedValue = root->db->getAttr(getKey());
+ if (cachedValue && !std::get_if<placeholder_t>(&cachedValue->second)) {
+ if (auto i = std::get_if<int_t>(&cachedValue->second)) {
+ debug("using cached Integer attribute '%s'", getAttrPathStr());
+ return i->x;
+ } else
+ throw TypeError("'%s' is not an Integer", getAttrPathStr());
+ }
+ }
+
+ auto & v = forceValue();
+
+ if (v.type() != nInt)
+ throw TypeError("'%s' is not an Integer", getAttrPathStr());
+
+ return v.integer;
+}
+
+std::vector<std::string> AttrCursor::getListOfStrings()
+{
+ if (root->db) {
+ if (!cachedValue)
+ cachedValue = root->db->getAttr(getKey());
+ if (cachedValue && !std::get_if<placeholder_t>(&cachedValue->second)) {
+ if (auto l = std::get_if<std::vector<std::string>>(&cachedValue->second)) {
+ debug("using cached list of strings attribute '%s'", getAttrPathStr());
+ return *l;
+ } else
+ throw TypeError("'%s' is not a list of strings", getAttrPathStr());
+ }
+ }
+
+ debug("evaluating uncached attribute '%s'", getAttrPathStr());
+
+ auto & v = getValue();
+ root->state.forceValue(v, noPos);
+
+ if (v.type() != nList)
+ throw TypeError("'%s' is not a list", getAttrPathStr());
+
+ std::vector<std::string> res;
+
+ for (auto & elem : v.listItems())
+ res.push_back(std::string(root->state.forceStringNoCtx(*elem)));
+
+ if (root->db)
+ cachedValue = {root->db->setListOfStrings(getKey(), res), res};
+
+ return res;
+}
+
std::vector<Symbol> AttrCursor::getAttrs()
{
if (root->db) {
if (!cachedValue)
- cachedValue = root->db->getAttr(getKey(), root->state.symbols);
+ cachedValue = root->db->getAttr(getKey());
if (cachedValue && !std::get_if<placeholder_t>(&cachedValue->second)) {
if (auto attrs = std::get_if<std::vector<Symbol>>(&cachedValue->second)) {
debug("using cached attrset attribute '%s'", getAttrPathStr());
return *attrs;
} else
- throw TypeError("'%s' is not an attribute set", getAttrPathStr());
+ root->state.debugThrowLastTrace(TypeError("'%s' is not an attribute set", getAttrPathStr()));
}
}
auto & v = forceValue();
if (v.type() != nAttrs)
- throw TypeError("'%s' is not an attribute set", getAttrPathStr());
+ root->state.debugThrowLastTrace(TypeError("'%s' is not an attribute set", getAttrPathStr()));
std::vector<Symbol> attrs;
for (auto & attr : *getValue().attrs)
attrs.push_back(attr.name);
- std::sort(attrs.begin(), attrs.end(), [](const Symbol & a, const Symbol & b) {
- return (const std::string &) a < (const std::string &) b;
+ std::sort(attrs.begin(), attrs.end(), [&](Symbol a, Symbol b) {
+ std::string_view sa = root->state.symbols[a], sb = root->state.symbols[b];
+ return sa < sb;
});
if (root->db)
diff --git a/src/libexpr/eval-cache.hh b/src/libexpr/eval-cache.hh
index 43b34ebcb..c93e55b93 100644
--- a/src/libexpr/eval-cache.hh
+++ b/src/libexpr/eval-cache.hh
@@ -33,7 +33,7 @@ public:
EvalState & state,
RootLoader rootLoader);
- std::shared_ptr<AttrCursor> getRoot();
+ ref<AttrCursor> getRoot();
};
enum AttrType {
@@ -44,15 +44,18 @@ enum AttrType {
Misc = 4,
Failed = 5,
Bool = 6,
+ ListOfStrings = 7,
+ Int = 8,
};
struct placeholder_t {};
struct missing_t {};
struct misc_t {};
struct failed_t {};
+struct int_t { NixInt x; };
typedef uint64_t AttrId;
typedef std::pair<AttrId, Symbol> AttrKey;
-typedef std::pair<std::string, std::vector<std::pair<Path, std::string>>> string_t;
+typedef std::pair<std::string, NixStringContext> string_t;
typedef std::variant<
std::vector<Symbol>,
@@ -61,7 +64,9 @@ typedef std::variant<
missing_t,
misc_t,
failed_t,
- bool
+ bool,
+ int_t,
+ std::vector<std::string>
> AttrValue;
class AttrCursor : public std::enable_shared_from_this<AttrCursor>
@@ -94,15 +99,19 @@ public:
std::string getAttrPathStr(Symbol name) const;
+ Suggestions getSuggestionsForAttr(Symbol name);
+
std::shared_ptr<AttrCursor> maybeGetAttr(Symbol name, bool forceErrors = false);
std::shared_ptr<AttrCursor> maybeGetAttr(std::string_view name);
- std::shared_ptr<AttrCursor> getAttr(Symbol name, bool forceErrors = false);
+ ref<AttrCursor> getAttr(Symbol name, bool forceErrors = false);
- std::shared_ptr<AttrCursor> getAttr(std::string_view name);
+ ref<AttrCursor> getAttr(std::string_view name);
- std::shared_ptr<AttrCursor> findAlongAttrPath(const std::vector<Symbol> & attrPath, bool force = false);
+ /* Get an attribute along a chain of attrsets. Note that this does
+ not auto-call functors or functions. */
+ OrSuggestions<ref<AttrCursor>> findAlongAttrPath(const std::vector<Symbol> & attrPath, bool force = false);
std::string getString();
@@ -110,6 +119,10 @@ public:
bool getBool();
+ NixInt getInt();
+
+ std::vector<std::string> getListOfStrings();
+
std::vector<Symbol> getAttrs();
bool isDerivation();
diff --git a/src/libexpr/eval-inline.hh b/src/libexpr/eval-inline.hh
index aef1f6351..f2f4ba725 100644
--- a/src/libexpr/eval-inline.hh
+++ b/src/libexpr/eval-inline.hh
@@ -2,29 +2,84 @@
#include "eval.hh"
-#define LocalNoInline(f) static f __attribute__((noinline)); f
-#define LocalNoInlineNoReturn(f) static f __attribute__((noinline, noreturn)); f
-
namespace nix {
-LocalNoInlineNoReturn(void throwEvalError(const Pos & pos, const char * s))
+/* Note: Various places expect the allocated memory to be zeroed. */
+[[gnu::always_inline]]
+inline void * allocBytes(size_t n)
+{
+ void * p;
+#if HAVE_BOEHMGC
+ p = GC_MALLOC(n);
+#else
+ p = calloc(n, 1);
+#endif
+ if (!p) throw std::bad_alloc();
+ return p;
+}
+
+
+[[gnu::always_inline]]
+Value * EvalState::allocValue()
{
- throw EvalError({
- .msg = hintfmt(s),
- .errPos = pos
- });
+#if HAVE_BOEHMGC
+ /* We use the boehm batch allocator to speed up allocations of Values (of which there are many).
+ GC_malloc_many returns a linked list of objects of the given size, where the first word
+ of each object is also the pointer to the next object in the list. This also means that we
+ have to explicitly clear the first word of every object we take. */
+ if (!*valueAllocCache) {
+ *valueAllocCache = GC_malloc_many(sizeof(Value));
+ if (!*valueAllocCache) throw std::bad_alloc();
+ }
+
+ /* GC_NEXT is a convenience macro for accessing the first word of an object.
+ Take the first list item, advance the list to the next item, and clear the next pointer. */
+ void * p = *valueAllocCache;
+ *valueAllocCache = GC_NEXT(p);
+ GC_NEXT(p) = nullptr;
+#else
+ void * p = allocBytes(sizeof(Value));
+#endif
+
+ nrValues++;
+ return (Value *) p;
}
-LocalNoInlineNoReturn(void throwTypeError(const Pos & pos, const char * s, const Value & v))
+
+[[gnu::always_inline]]
+Env & EvalState::allocEnv(size_t size)
{
- throw TypeError({
- .msg = hintfmt(s, showType(v)),
- .errPos = pos
- });
+ nrEnvs++;
+ nrValuesInEnvs += size;
+
+ Env * env;
+
+#if HAVE_BOEHMGC
+ if (size == 1) {
+ /* see allocValue for explanations. */
+ if (!*env1AllocCache) {
+ *env1AllocCache = GC_malloc_many(sizeof(Env) + sizeof(Value *));
+ if (!*env1AllocCache) throw std::bad_alloc();
+ }
+
+ void * p = *env1AllocCache;
+ *env1AllocCache = GC_NEXT(p);
+ GC_NEXT(p) = nullptr;
+ env = (Env *) p;
+ } else
+#endif
+ env = (Env *) allocBytes(sizeof(Env) + size * sizeof(Value *));
+
+ env->type = Env::Plain;
+
+ /* We assume that env->values has been cleared by the allocator; maybeThunk() and lookupVar fromWith expect this. */
+
+ return *env;
}
-void EvalState::forceValue(Value & v, const Pos & pos)
+[[gnu::always_inline]]
+void EvalState::forceValue(Value & v, const PosIdx pos)
{
forceValue(v, [&]() { return pos; });
}
@@ -52,13 +107,15 @@ void EvalState::forceValue(Value & v, Callable getPos)
}
-inline void EvalState::forceAttrs(Value & v, const Pos & pos)
+[[gnu::always_inline]]
+inline void EvalState::forceAttrs(Value & v, const PosIdx pos)
{
forceAttrs(v, [&]() { return pos; });
}
template <typename Callable>
+[[gnu::always_inline]]
inline void EvalState::forceAttrs(Value & v, Callable getPos)
{
forceValue(v, getPos);
@@ -67,25 +124,13 @@ inline void EvalState::forceAttrs(Value & v, Callable getPos)
}
-inline void EvalState::forceList(Value & v, const Pos & pos)
+[[gnu::always_inline]]
+inline void EvalState::forceList(Value & v, const PosIdx pos)
{
forceValue(v, pos);
if (!v.isList())
throwTypeError(pos, "value is %1% while a list was expected", v);
}
-/* Note: Various places expect the allocated memory to be zeroed. */
-inline void * allocBytes(size_t n)
-{
- void * p;
-#if HAVE_BOEHMGC
- p = GC_MALLOC(n);
-#else
- p = calloc(n, 1);
-#endif
- if (!p) throw std::bad_alloc();
- return p;
-}
-
}
diff --git a/src/libexpr/eval.cc b/src/libexpr/eval.cc
index 60f0bf08c..e3716f217 100644
--- a/src/libexpr/eval.cc
+++ b/src/libexpr/eval.cc
@@ -18,6 +18,7 @@
#include <sys/resource.h>
#include <iostream>
#include <fstream>
+#include <functional>
#include <sys/resource.h>
@@ -36,7 +37,6 @@
namespace nix {
-
static char * allocString(size_t size)
{
char * t;
@@ -63,9 +63,15 @@ static char * dupString(const char * s)
}
-static char * dupStringWithLen(const char * s, size_t size)
+// When there's no need to write to the string, we can optimize away empty
+// string allocations.
+// This function handles makeImmutableStringWithLen(null, 0) by returning the
+// empty string.
+static const char * makeImmutableStringWithLen(const char * s, size_t size)
{
char * t;
+ if (size == 0)
+ return "";
#if HAVE_BOEHMGC
t = GC_STRNDUP(s, size);
#else
@@ -75,6 +81,10 @@ static char * dupStringWithLen(const char * s, size_t size)
return t;
}
+static inline const char * makeImmutableString(std::string_view s) {
+ return makeImmutableStringWithLen(s.data(), s.size());
+}
+
RootValue allocRootValue(Value * v)
{
@@ -86,25 +96,21 @@ RootValue allocRootValue(Value * v)
}
-void printValue(std::ostream & str, std::set<const Value *> & active, const Value & v)
+void Value::print(const SymbolTable & symbols, std::ostream & str,
+ std::set<const void *> * seen) const
{
checkInterrupt();
- if (!active.insert(&v).second) {
- str << "<CYCLE>";
- return;
- }
-
- switch (v.internalType) {
+ switch (internalType) {
case tInt:
- str << v.integer;
+ str << integer;
break;
case tBool:
- str << (v.boolean ? "true" : "false");
+ str << (boolean ? "true" : "false");
break;
case tString:
str << "\"";
- for (const char * i = v.string.s; *i; i++)
+ for (const char * i = string.s; *i; i++)
if (*i == '\"' || *i == '\\') str << "\\" << *i;
else if (*i == '\n') str << "\\n";
else if (*i == '\r') str << "\\r";
@@ -114,30 +120,41 @@ void printValue(std::ostream & str, std::set<const Value *> & active, const Valu
str << "\"";
break;
case tPath:
- str << v.path; // !!! escaping?
+ str << path; // !!! escaping?
break;
case tNull:
str << "null";
break;
case tAttrs: {
- str << "{ ";
- for (auto & i : v.attrs->lexicographicOrder()) {
- str << i->name << " = ";
- printValue(str, active, *i->value);
- str << "; ";
+ if (seen && !attrs->empty() && !seen->insert(attrs).second)
+ str << "«repeated»";
+ else {
+ str << "{ ";
+ for (auto & i : attrs->lexicographicOrder(symbols)) {
+ str << symbols[i->name] << " = ";
+ i->value->print(symbols, str, seen);
+ str << "; ";
+ }
+ str << "}";
}
- str << "}";
break;
}
case tList1:
case tList2:
case tListN:
- str << "[ ";
- for (auto v2 : v.listItems()) {
- printValue(str, active, *v2);
- str << " ";
+ if (seen && listSize() && !seen->insert(listElems()).second)
+ str << "«repeated»";
+ else {
+ str << "[ ";
+ for (auto v2 : listItems()) {
+ if (v2)
+ v2->print(symbols, str, seen);
+ else
+ str << "(nullptr)";
+ str << " ";
+ }
+ str << "]";
}
- str << "]";
break;
case tThunk:
case tApp:
@@ -153,24 +170,34 @@ void printValue(std::ostream & str, std::set<const Value *> & active, const Valu
str << "<PRIMOP-APP>";
break;
case tExternal:
- str << *v.external;
+ str << *external;
break;
case tFloat:
- str << v.fpoint;
+ str << fpoint;
break;
default:
abort();
}
+}
+
- active.erase(&v);
+void Value::print(const SymbolTable & symbols, std::ostream & str, bool showRepeated) const
+{
+ std::set<const void *> seen;
+ print(symbols, str, showRepeated ? nullptr : &seen);
}
+// Pretty print types for assertion errors
+std::ostream & operator << (std::ostream & os, const ValueType t) {
+ os << showType(t);
+ return os;
+}
-std::ostream & operator << (std::ostream & str, const Value & v)
+std::string printValue(const EvalState & state, const Value & v)
{
- std::set<const Value *> active;
- printValue(str, active, v);
- return str;
+ std::ostringstream out;
+ v.print(state.symbols, out);
+ return out.str();
}
@@ -219,10 +246,10 @@ std::string showType(const Value & v)
}
}
-Pos Value::determinePos(const Pos & pos) const
+PosIdx Value::determinePos(const PosIdx pos) const
{
switch (internalType) {
- case tAttrs: return *attrs->pos;
+ case tAttrs: return attrs->pos;
case tLambda: return lambda.fun->pos;
case tApp: return app.left->determinePos(pos);
default: return pos;
@@ -291,7 +318,7 @@ static BoehmGCStackAllocator boehmGCStackAllocator;
static Symbol getName(const AttrName & name, EvalState & state, Env & env)
{
- if (name.symbol.set()) {
+ if (name.symbol) {
return name.symbol;
} else {
Value nameValue;
@@ -419,6 +446,7 @@ EvalState::EvalState(
, sBuilder(symbols.create("builder"))
, sArgs(symbols.create("args"))
, sContentAddressed(symbols.create("__contentAddressed"))
+ , sImpure(symbols.create("__impure"))
, sOutputHash(symbols.create("outputHash"))
, sOutputHashAlgo(symbols.create("outputHashAlgo"))
, sOutputHashMode(symbols.create("outputHashMode"))
@@ -431,18 +459,25 @@ EvalState::EvalState(
, sKey(symbols.create("key"))
, sPath(symbols.create("path"))
, sPrefix(symbols.create("prefix"))
+ , sOutputSpecified(symbols.create("outputSpecified"))
, repair(NoRepair)
, emptyBindings(0)
, store(store)
, buildStore(buildStore ? buildStore : store)
+ , debugRepl(nullptr)
+ , debugStop(false)
+ , debugQuit(false)
+ , trylevel(0)
, regexCache(makeRegexCache())
#if HAVE_BOEHMGC
, valueAllocCache(std::allocate_shared<void *>(traceable_allocator<void *>(), nullptr))
+ , env1AllocCache(std::allocate_shared<void *>(traceable_allocator<void *>(), nullptr))
#else
, valueAllocCache(std::make_shared<void *>(nullptr))
+ , env1AllocCache(std::make_shared<void *>(nullptr))
#endif
, baseEnv(allocEnv(128))
- , staticBaseEnv(false, 0)
+ , staticBaseEnv{std::make_shared<StaticEnv>(false, nullptr)}
{
countCalls = getEnv("NIX_COUNT_CALLS").value_or("0") != "0";
@@ -488,23 +523,6 @@ EvalState::~EvalState()
}
-void EvalState::requireExperimentalFeatureOnEvaluation(
- const ExperimentalFeature & feature,
- const std::string_view fName,
- const Pos & pos)
-{
- if (!settings.isExperimentalFeatureEnabled(feature)) {
- throw EvalError({
- .msg = hintfmt(
- "Cannot call '%2%' because experimental Nix feature '%1%' is disabled. You can enable it via '--extra-experimental-features %1%'.",
- feature,
- fName
- ),
- .errPos = pos
- });
- }
-}
-
void EvalState::allowPath(const Path & path)
{
if (allowedPaths)
@@ -517,6 +535,14 @@ void EvalState::allowPath(const StorePath & storePath)
allowedPaths->insert(store->toRealPath(storePath));
}
+void EvalState::allowAndSetStorePathString(const StorePath & storePath, Value & v)
+{
+ allowPath(storePath);
+
+ auto path = store->printStorePath(storePath);
+ v.mkString(path, PathSet({path}));
+}
+
Path EvalState::checkSourcePath(const Path & path_)
{
if (!allowedPaths) return path_;
@@ -617,7 +643,7 @@ Value * EvalState::addConstant(const std::string & name, Value & v)
void EvalState::addConstant(const std::string & name, Value * v)
{
- staticBaseEnv.vars.emplace_back(symbols.create(name), baseEnvDispl);
+ staticBaseEnv->vars.emplace_back(symbols.create(name), baseEnvDispl);
baseEnv.values[baseEnvDispl++] = v;
auto name2 = name.substr(0, 2) == "__" ? name.substr(2) : name;
baseEnv.values[0]->attrs->push_back(Attr(symbols.create(name2), v));
@@ -628,21 +654,21 @@ Value * EvalState::addPrimOp(const std::string & name,
size_t arity, PrimOpFun primOp)
{
auto name2 = name.substr(0, 2) == "__" ? name.substr(2) : name;
- Symbol sym = symbols.create(name2);
+ auto sym = symbols.create(name2);
/* Hack to make constants lazy: turn them into a application of
the primop to a dummy value. */
if (arity == 0) {
auto vPrimOp = allocValue();
- vPrimOp->mkPrimOp(new PrimOp { .fun = primOp, .arity = 1, .name = sym });
+ vPrimOp->mkPrimOp(new PrimOp { .fun = primOp, .arity = 1, .name = name2 });
Value v;
v.mkApp(vPrimOp, vPrimOp);
return addConstant(name, v);
}
Value * v = allocValue();
- v->mkPrimOp(new PrimOp { .fun = primOp, .arity = arity, .name = sym });
- staticBaseEnv.vars.emplace_back(symbols.create(name), baseEnvDispl);
+ v->mkPrimOp(new PrimOp { .fun = primOp, .arity = arity, .name = name2 });
+ staticBaseEnv->vars.emplace_back(symbols.create(name), baseEnvDispl);
baseEnv.values[baseEnvDispl++] = v;
baseEnv.values[0]->attrs->push_back(Attr(sym, v));
return v;
@@ -656,21 +682,21 @@ Value * EvalState::addPrimOp(PrimOp && primOp)
if (primOp.arity == 0) {
primOp.arity = 1;
auto vPrimOp = allocValue();
- vPrimOp->mkPrimOp(new PrimOp(std::move(primOp)));
+ vPrimOp->mkPrimOp(new PrimOp(primOp));
Value v;
v.mkApp(vPrimOp, vPrimOp);
return addConstant(primOp.name, v);
}
- Symbol envName = primOp.name;
+ auto envName = symbols.create(primOp.name);
if (hasPrefix(primOp.name, "__"))
- primOp.name = symbols.create(std::string(primOp.name, 2));
+ primOp.name = primOp.name.substr(2);
Value * v = allocValue();
- v->mkPrimOp(new PrimOp(std::move(primOp)));
- staticBaseEnv.vars.emplace_back(envName, baseEnvDispl);
+ v->mkPrimOp(new PrimOp(primOp));
+ staticBaseEnv->vars.emplace_back(envName, baseEnvDispl);
baseEnv.values[baseEnvDispl++] = v;
- baseEnv.values[0]->attrs->push_back(Attr(primOp.name, v));
+ baseEnv.values[0]->attrs->push_back(Attr(symbols.create(primOp.name), v));
return v;
}
@@ -687,7 +713,7 @@ std::optional<EvalState::Doc> EvalState::getDoc(Value & v)
auto v2 = &v;
if (v2->primOp->doc)
return Doc {
- .pos = noPos,
+ .pos = {},
.name = v2->primOp->name,
.arity = v2->primOp->arity,
.args = v2->primOp->args,
@@ -698,105 +724,333 @@ std::optional<EvalState::Doc> EvalState::getDoc(Value & v)
}
+// just for the current level of StaticEnv, not the whole chain.
+void printStaticEnvBindings(const SymbolTable & st, const StaticEnv & se)
+{
+ std::cout << ANSI_MAGENTA;
+ for (auto & i : se.vars)
+ std::cout << st[i.first] << " ";
+ std::cout << ANSI_NORMAL;
+ std::cout << std::endl;
+}
+
+// just for the current level of Env, not the whole chain.
+void printWithBindings(const SymbolTable & st, const Env & env)
+{
+ if (env.type == Env::HasWithAttrs) {
+ std::cout << "with: ";
+ std::cout << ANSI_MAGENTA;
+ Bindings::iterator j = env.values[0]->attrs->begin();
+ while (j != env.values[0]->attrs->end()) {
+ std::cout << st[j->name] << " ";
+ ++j;
+ }
+ std::cout << ANSI_NORMAL;
+ std::cout << std::endl;
+ }
+}
+
+void printEnvBindings(const SymbolTable & st, const StaticEnv & se, const Env & env, int lvl)
+{
+ std::cout << "Env level " << lvl << std::endl;
+
+ if (se.up && env.up) {
+ std::cout << "static: ";
+ printStaticEnvBindings(st, se);
+ printWithBindings(st, env);
+ std::cout << std::endl;
+ printEnvBindings(st, *se.up, *env.up, ++lvl);
+ } else {
+ std::cout << ANSI_MAGENTA;
+ // for the top level, don't print the double underscore ones;
+ // they are in builtins.
+ for (auto & i : se.vars)
+ if (!hasPrefix(st[i.first], "__"))
+ std::cout << st[i.first] << " ";
+ std::cout << ANSI_NORMAL;
+ std::cout << std::endl;
+ printWithBindings(st, env); // probably nothing there for the top level.
+ std::cout << std::endl;
+
+ }
+}
+
+void printEnvBindings(const EvalState &es, const Expr & expr, const Env & env)
+{
+ // just print the names for now
+ auto se = es.getStaticEnv(expr);
+ if (se)
+ printEnvBindings(es.symbols, *se, env, 0);
+}
+
+void mapStaticEnvBindings(const SymbolTable & st, const StaticEnv & se, const Env & env, ValMap & vm)
+{
+ // add bindings for the next level up first, so that the bindings for this level
+ // override the higher levels.
+ // The top level bindings (builtins) are skipped since they are added for us by initEnv()
+ if (env.up && se.up) {
+ mapStaticEnvBindings(st, *se.up, *env.up, vm);
+
+ if (env.type == Env::HasWithAttrs) {
+ // add 'with' bindings.
+ Bindings::iterator j = env.values[0]->attrs->begin();
+ while (j != env.values[0]->attrs->end()) {
+ vm[st[j->name]] = j->value;
+ ++j;
+ }
+ } else {
+ // iterate through staticenv bindings and add them.
+ for (auto & i : se.vars)
+ vm[st[i.first]] = env.values[i.second];
+ }
+ }
+}
+
+std::unique_ptr<ValMap> mapStaticEnvBindings(const SymbolTable & st, const StaticEnv & se, const Env & env)
+{
+ auto vm = std::make_unique<ValMap>();
+ mapStaticEnvBindings(st, se, env, *vm);
+ return vm;
+}
+
+void EvalState::runDebugRepl(const Error * error, const Env & env, const Expr & expr)
+{
+ // double check we've got the debugRepl function pointer.
+ if (!debugRepl)
+ return;
+
+ auto dts =
+ error && expr.getPos()
+ ? std::make_unique<DebugTraceStacker>(
+ *this,
+ DebugTrace {
+ .pos = error->info().errPos ? *error->info().errPos : positions[expr.getPos()],
+ .expr = expr,
+ .env = env,
+ .hint = error->info().msg,
+ .isError = true
+ })
+ : nullptr;
+
+ if (error)
+ {
+ printError("%s\n\n", error->what());
+
+ if (trylevel > 0 && error->info().level != lvlInfo)
+ printError("This exception occurred in a 'tryEval' call. Use " ANSI_GREEN "--ignore-try" ANSI_NORMAL " to skip these.\n");
+
+ printError(ANSI_BOLD "Starting REPL to allow you to inspect the current state of the evaluator.\n" ANSI_NORMAL);
+ }
+
+ auto se = getStaticEnv(expr);
+ if (se) {
+ auto vm = mapStaticEnvBindings(symbols, *se.get(), env);
+ (debugRepl)(ref<EvalState>(shared_from_this()), *vm);
+ }
+}
+
/* Every "format" object (even temporary) takes up a few hundred bytes
of stack space, which is a real killer in the recursive
evaluator. So here are some helper functions for throwing
exceptions. */
+void EvalState::throwEvalError(const PosIdx pos, const char * s, Env & env, Expr & expr)
+{
+ debugThrow(EvalError({
+ .msg = hintfmt(s),
+ .errPos = positions[pos]
+ }), env, expr);
+}
-LocalNoInlineNoReturn(void throwEvalError(const char * s, const std::string & s2))
+void EvalState::throwEvalError(const PosIdx pos, const char * s)
{
- throw EvalError(s, s2);
+ debugThrowLastTrace(EvalError({
+ .msg = hintfmt(s),
+ .errPos = positions[pos]
+ }));
}
-LocalNoInlineNoReturn(void throwEvalError(const Pos & pos, const char * s, const std::string & s2))
+void EvalState::throwEvalError(const char * s, const std::string & s2)
{
- throw EvalError({
+ debugThrowLastTrace(EvalError(s, s2));
+}
+
+void EvalState::throwEvalError(const PosIdx pos, const Suggestions & suggestions, const char * s,
+ const std::string & s2, Env & env, Expr & expr)
+{
+ debugThrow(EvalError(ErrorInfo{
.msg = hintfmt(s, s2),
- .errPos = pos
- });
+ .errPos = positions[pos],
+ .suggestions = suggestions,
+ }), env, expr);
}
-LocalNoInlineNoReturn(void throwEvalError(const char * s, const std::string & s2, const std::string & s3))
+void EvalState::throwEvalError(const PosIdx pos, const char * s, const std::string & s2)
{
- throw EvalError(s, s2, s3);
+ debugThrowLastTrace(EvalError({
+ .msg = hintfmt(s, s2),
+ .errPos = positions[pos]
+ }));
}
-LocalNoInlineNoReturn(void throwEvalError(const Pos & pos, const char * s, const std::string & s2, const std::string & s3))
+void EvalState::throwEvalError(const PosIdx pos, const char * s, const std::string & s2, Env & env, Expr & expr)
{
- throw EvalError({
- .msg = hintfmt(s, s2, s3),
- .errPos = pos
- });
+ debugThrow(EvalError({
+ .msg = hintfmt(s, s2),
+ .errPos = positions[pos]
+ }), env, expr);
+}
+
+void EvalState::throwEvalError(const char * s, const std::string & s2,
+ const std::string & s3)
+{
+ debugThrowLastTrace(EvalError({
+ .msg = hintfmt(s, s2),
+ .errPos = positions[noPos]
+ }));
+}
+
+void EvalState::throwEvalError(const PosIdx pos, const char * s, const std::string & s2,
+ const std::string & s3)
+{
+ debugThrowLastTrace(EvalError({
+ .msg = hintfmt(s, s2),
+ .errPos = positions[pos]
+ }));
}
-LocalNoInlineNoReturn(void throwEvalError(const Pos & p1, const char * s, const Symbol & sym, const Pos & p2))
+void EvalState::throwEvalError(const PosIdx pos, const char * s, const std::string & s2,
+ const std::string & s3, Env & env, Expr & expr)
+{
+ debugThrow(EvalError({
+ .msg = hintfmt(s, s2),
+ .errPos = positions[pos]
+ }), env, expr);
+}
+
+void EvalState::throwEvalError(const PosIdx p1, const char * s, const Symbol sym, const PosIdx p2, Env & env, Expr & expr)
{
// p1 is where the error occurred; p2 is a position mentioned in the message.
- throw EvalError({
- .msg = hintfmt(s, sym, p2),
- .errPos = p1
- });
+ debugThrow(EvalError({
+ .msg = hintfmt(s, symbols[sym], positions[p2]),
+ .errPos = positions[p1]
+ }), env, expr);
}
-LocalNoInlineNoReturn(void throwTypeError(const Pos & pos, const char * s))
+void EvalState::throwTypeError(const PosIdx pos, const char * s, const Value & v)
{
- throw TypeError({
+ debugThrowLastTrace(TypeError({
+ .msg = hintfmt(s, showType(v)),
+ .errPos = positions[pos]
+ }));
+}
+
+void EvalState::throwTypeError(const PosIdx pos, const char * s, const Value & v, Env & env, Expr & expr)
+{
+ debugThrow(TypeError({
+ .msg = hintfmt(s, showType(v)),
+ .errPos = positions[pos]
+ }), env, expr);
+}
+
+void EvalState::throwTypeError(const PosIdx pos, const char * s)
+{
+ debugThrowLastTrace(TypeError({
.msg = hintfmt(s),
- .errPos = pos
- });
+ .errPos = positions[pos]
+ }));
}
-LocalNoInlineNoReturn(void throwTypeError(const Pos & pos, const char * s, const ExprLambda & fun, const Symbol & s2))
+void EvalState::throwTypeError(const PosIdx pos, const char * s, const ExprLambda & fun,
+ const Symbol s2, Env & env, Expr &expr)
{
- throw TypeError({
- .msg = hintfmt(s, fun.showNamePos(), s2),
- .errPos = pos
- });
+ debugThrow(TypeError({
+ .msg = hintfmt(s, fun.showNamePos(*this), symbols[s2]),
+ .errPos = positions[pos]
+ }), env, expr);
}
-LocalNoInlineNoReturn(void throwTypeError(const char * s, const Value & v))
+void EvalState::throwTypeError(const PosIdx pos, const Suggestions & suggestions, const char * s,
+ const ExprLambda & fun, const Symbol s2, Env & env, Expr &expr)
{
- throw TypeError(s, showType(v));
+ debugThrow(TypeError(ErrorInfo {
+ .msg = hintfmt(s, fun.showNamePos(*this), symbols[s2]),
+ .errPos = positions[pos],
+ .suggestions = suggestions,
+ }), env, expr);
}
-LocalNoInlineNoReturn(void throwAssertionError(const Pos & pos, const char * s, const std::string & s1))
+void EvalState::throwTypeError(const char * s, const Value & v, Env & env, Expr &expr)
{
- throw AssertionError({
+ debugThrow(TypeError({
+ .msg = hintfmt(s, showType(v)),
+ .errPos = positions[expr.getPos()],
+ }), env, expr);
+}
+
+void EvalState::throwAssertionError(const PosIdx pos, const char * s, const std::string & s1, Env & env, Expr &expr)
+{
+ debugThrow(AssertionError({
.msg = hintfmt(s, s1),
- .errPos = pos
- });
+ .errPos = positions[pos]
+ }), env, expr);
}
-LocalNoInlineNoReturn(void throwUndefinedVarError(const Pos & pos, const char * s, const std::string & s1))
+void EvalState::throwUndefinedVarError(const PosIdx pos, const char * s, const std::string & s1, Env & env, Expr &expr)
{
- throw UndefinedVarError({
+ debugThrow(UndefinedVarError({
.msg = hintfmt(s, s1),
- .errPos = pos
- });
+ .errPos = positions[pos]
+ }), env, expr);
}
-LocalNoInlineNoReturn(void throwMissingArgumentError(const Pos & pos, const char * s, const std::string & s1))
+void EvalState::throwMissingArgumentError(const PosIdx pos, const char * s, const std::string & s1, Env & env, Expr &expr)
{
- throw MissingArgumentError({
+ debugThrow(MissingArgumentError({
.msg = hintfmt(s, s1),
- .errPos = pos
- });
+ .errPos = positions[pos]
+ }), env, expr);
}
-LocalNoInline(void addErrorTrace(Error & e, const char * s, const std::string & s2))
+void EvalState::addErrorTrace(Error & e, const char * s, const std::string & s2) const
{
e.addTrace(std::nullopt, s, s2);
}
-LocalNoInline(void addErrorTrace(Error & e, const Pos & pos, const char * s, const std::string & s2))
+void EvalState::addErrorTrace(Error & e, const PosIdx pos, const char * s, const std::string & s2) const
{
- e.addTrace(pos, s, s2);
+ e.addTrace(positions[pos], s, s2);
}
+static std::unique_ptr<DebugTraceStacker> makeDebugTraceStacker(
+ EvalState & state,
+ Expr & expr,
+ Env & env,
+ std::optional<ErrPos> pos,
+ const char * s,
+ const std::string & s2)
+{
+ return std::make_unique<DebugTraceStacker>(state,
+ DebugTrace {
+ .pos = pos,
+ .expr = expr,
+ .env = env,
+ .hint = hintfmt(s, s2),
+ .isError = false
+ });
+}
+
+DebugTraceStacker::DebugTraceStacker(EvalState & evalState, DebugTrace t)
+ : evalState(evalState)
+ , trace(std::move(t))
+{
+ evalState.debugTraces.push_front(trace);
+ if (evalState.debugStop && evalState.debugRepl)
+ evalState.runDebugRepl(nullptr, trace.env, trace.expr);
+}
void Value::mkString(std::string_view s)
{
- mkString(dupStringWithLen(s.data(), s.size()));
+ mkString(makeImmutableString(s));
}
@@ -827,7 +1081,7 @@ void Value::mkStringMove(const char * s, const PathSet & context)
void Value::mkPath(std::string_view s)
{
- mkPath(dupStringWithLen(s.data(), s.size()));
+ mkPath(makeImmutableString(s));
}
@@ -847,52 +1101,15 @@ inline Value * EvalState::lookupVar(Env * env, const ExprVar & var, bool noEval)
}
Bindings::iterator j = env->values[0]->attrs->find(var.name);
if (j != env->values[0]->attrs->end()) {
- if (countCalls) attrSelects[*j->pos]++;
+ if (countCalls) attrSelects[j->pos]++;
return j->value;
}
if (!env->prevWith)
- throwUndefinedVarError(var.pos, "undefined variable '%1%'", var.name);
+ throwUndefinedVarError(var.pos, "undefined variable '%1%'", symbols[var.name], *env, const_cast<ExprVar&>(var));
for (size_t l = env->prevWith; l; --l, env = env->up) ;
}
}
-
-Value * EvalState::allocValue()
-{
- /* We use the boehm batch allocator to speed up allocations of Values (of which there are many).
- GC_malloc_many returns a linked list of objects of the given size, where the first word
- of each object is also the pointer to the next object in the list. This also means that we
- have to explicitly clear the first word of every object we take. */
- if (!*valueAllocCache) {
- *valueAllocCache = GC_malloc_many(sizeof(Value));
- if (!*valueAllocCache) throw std::bad_alloc();
- }
-
- /* GC_NEXT is a convenience macro for accessing the first word of an object.
- Take the first list item, advance the list to the next item, and clear the next pointer. */
- void * p = *valueAllocCache;
- GC_PTR_STORE_AND_DIRTY(&*valueAllocCache, GC_NEXT(p));
- GC_NEXT(p) = nullptr;
-
- nrValues++;
- auto v = (Value *) p;
- return v;
-}
-
-
-Env & EvalState::allocEnv(size_t size)
-{
- nrEnvs++;
- nrValuesInEnvs += size;
- Env * env = (Env *) allocBytes(sizeof(Env) + size * sizeof(Value *));
- env->type = Env::Plain;
-
- /* We assume that env->values has been cleared by the allocator; maybeThunk() and lookupVar fromWith expect this. */
-
- return *env;
-}
-
-
void EvalState::mkList(Value & v, size_t size)
{
v.mkList(size);
@@ -917,13 +1134,14 @@ void EvalState::mkThunk_(Value & v, Expr * expr)
}
-void EvalState::mkPos(Value & v, ptr<Pos> pos)
+void EvalState::mkPos(Value & v, PosIdx p)
{
- if (pos->file.set()) {
+ auto pos = positions[p];
+ if (!pos.file.empty()) {
auto attrs = buildBindings(3);
- attrs.alloc(sFile).mkString(pos->file);
- attrs.alloc(sLine).mkInt(pos->line);
- attrs.alloc(sColumn).mkInt(pos->column);
+ attrs.alloc(sFile).mkString(pos.file);
+ attrs.alloc(sLine).mkInt(pos.line);
+ attrs.alloc(sColumn).mkInt(pos.column);
v.mkAttrs(attrs);
} else
v.mkNull();
@@ -1024,6 +1242,15 @@ void EvalState::cacheFile(
fileParseCache[resolvedPath] = e;
try {
+ auto dts = debugRepl
+ ? makeDebugTraceStacker(
+ *this,
+ *e,
+ this->baseEnv,
+ e->getPos() ? std::optional(ErrPos(positions[e->getPos()])) : std::nullopt,
+ "while evaluating the file '%1%':", resolvedPath)
+ : nullptr;
+
// Enforce that 'flake.nix' is a direct attrset, not a
// computation.
if (mustBeTrivial &&
@@ -1051,17 +1278,17 @@ inline bool EvalState::evalBool(Env & env, Expr * e)
Value v;
e->eval(*this, env, v);
if (v.type() != nBool)
- throwTypeError("value is %1% while a Boolean was expected", v);
+ throwTypeError(noPos, "value is %1% while a Boolean was expected", v, env, *e);
return v.boolean;
}
-inline bool EvalState::evalBool(Env & env, Expr * e, const Pos & pos)
+inline bool EvalState::evalBool(Env & env, Expr * e, const PosIdx pos)
{
Value v;
e->eval(*this, env, v);
if (v.type() != nBool)
- throwTypeError(pos, "value is %1% while a Boolean was expected", v);
+ throwTypeError(pos, "value is %1% while a Boolean was expected", v, env, *e);
return v.boolean;
}
@@ -1070,7 +1297,7 @@ inline void EvalState::evalAttrs(Env & env, Expr * e, Value & v)
{
e->eval(*this, env, v);
if (v.type() != nAttrs)
- throwTypeError("value is %1% while a set was expected", v);
+ throwTypeError(noPos, "value is %1% while a set was expected", v, env, *e);
}
@@ -1130,7 +1357,7 @@ void ExprAttrs::eval(EvalState & state, Env & env, Value & v)
} else
vAttr = i.second.e->maybeThunk(state, i.second.inherited ? env : env2);
env2.values[displ++] = vAttr;
- v.attrs->push_back(Attr(i.first, vAttr, ptr(&i.second.pos)));
+ v.attrs->push_back(Attr(i.first, vAttr, i.second.pos));
}
/* If the rec contains an attribute called `__overrides', then
@@ -1162,7 +1389,7 @@ void ExprAttrs::eval(EvalState & state, Env & env, Value & v)
else
for (auto & i : attrs)
- v.attrs->push_back(Attr(i.first, i.second.e->maybeThunk(state, env), ptr(&i.second.pos)));
+ v.attrs->push_back(Attr(i.first, i.second.e->maybeThunk(state, env), i.second.pos));
/* Dynamic attrs apply *after* rec and __overrides. */
for (auto & i : dynamicAttrs) {
@@ -1172,18 +1399,18 @@ void ExprAttrs::eval(EvalState & state, Env & env, Value & v)
if (nameVal.type() == nNull)
continue;
state.forceStringNoCtx(nameVal);
- Symbol nameSym = state.symbols.create(nameVal.string.s);
+ auto nameSym = state.symbols.create(nameVal.string.s);
Bindings::iterator j = v.attrs->find(nameSym);
if (j != v.attrs->end())
- throwEvalError(i.pos, "dynamic attribute '%1%' already defined at %2%", nameSym, *j->pos);
+ state.throwEvalError(i.pos, "dynamic attribute '%1%' already defined at %2%", nameSym, j->pos, env, *this);
i.valueExpr->setName(nameSym);
/* Keep sorted order so find can catch duplicates */
- v.attrs->push_back(Attr(nameSym, i.valueExpr->maybeThunk(state, *dynamicEnv), ptr(&i.pos)));
+ v.attrs->push_back(Attr(nameSym, i.valueExpr->maybeThunk(state, *dynamicEnv), i.pos));
v.attrs->sort(); // FIXME: inefficient
}
- v.attrs->pos = ptr(&pos);
+ v.attrs->pos = pos;
}
@@ -1228,10 +1455,12 @@ static std::string showAttrPath(EvalState & state, Env & env, const AttrPath & a
for (auto & i : attrPath) {
if (!first) out << '.'; else first = false;
try {
- out << getName(i, state, env);
+ out << state.symbols[getName(i, state, env)];
} catch (Error & e) {
- assert(!i.symbol.set());
- out << "\"${" << *i.expr << "}\"";
+ assert(!i.symbol);
+ out << "\"${";
+ i.expr->show(state.symbols, out);
+ out << "}\"";
}
}
return out.str();
@@ -1241,17 +1470,26 @@ static std::string showAttrPath(EvalState & state, Env & env, const AttrPath & a
void ExprSelect::eval(EvalState & state, Env & env, Value & v)
{
Value vTmp;
- ptr<Pos> pos2(&noPos);
+ PosIdx pos2;
Value * vAttrs = &vTmp;
e->eval(state, env, vTmp);
try {
+ auto dts = state.debugRepl
+ ? makeDebugTraceStacker(
+ state,
+ *this,
+ env,
+ state.positions[pos2],
+ "while evaluating the attribute '%1%'",
+ showAttrPath(state, env, attrPath))
+ : nullptr;
for (auto & i : attrPath) {
state.nrLookups++;
Bindings::iterator j;
- Symbol name = getName(i, state, env);
+ auto name = getName(i, state, env);
if (def) {
state.forceValue(*vAttrs, pos);
if (vAttrs->type() != nAttrs ||
@@ -1262,19 +1500,27 @@ void ExprSelect::eval(EvalState & state, Env & env, Value & v)
}
} else {
state.forceAttrs(*vAttrs, pos);
- if ((j = vAttrs->attrs->find(name)) == vAttrs->attrs->end())
- throwEvalError(pos, "attribute '%1%' missing", name);
+ if ((j = vAttrs->attrs->find(name)) == vAttrs->attrs->end()) {
+ std::set<std::string> allAttrNames;
+ for (auto & attr : *vAttrs->attrs)
+ allAttrNames.insert(state.symbols[attr.name]);
+ state.throwEvalError(
+ pos,
+ Suggestions::bestMatches(allAttrNames, state.symbols[name]),
+ "attribute '%1%' missing", state.symbols[name], env, *this);
+ }
}
vAttrs = j->value;
pos2 = j->pos;
- if (state.countCalls) state.attrSelects[*pos2]++;
+ if (state.countCalls) state.attrSelects[pos2]++;
}
- state.forceValue(*vAttrs, (*pos2 != noPos ? *pos2 : this->pos ) );
+ state.forceValue(*vAttrs, (pos2 ? pos2 : this->pos ) );
} catch (Error & e) {
- if (*pos2 != noPos && pos2->file != state.sDerivationNix)
- addErrorTrace(e, *pos2, "while evaluating the attribute '%1%'",
+ auto pos2r = state.positions[pos2];
+ if (pos2 && pos2r.file != state.derivationNixPath)
+ state.addErrorTrace(e, pos2, "while evaluating the attribute '%1%'",
showAttrPath(state, env, attrPath));
throw;
}
@@ -1293,7 +1539,7 @@ void ExprOpHasAttr::eval(EvalState & state, Env & env, Value & v)
for (auto & i : attrPath) {
state.forceValue(*vAttrs, noPos);
Bindings::iterator j;
- Symbol name = getName(i, state, env);
+ auto name = getName(i, state, env);
if (vAttrs->type() != nAttrs ||
(j = vAttrs->attrs->find(name)) == vAttrs->attrs->end())
{
@@ -1314,9 +1560,11 @@ void ExprLambda::eval(EvalState & state, Env & env, Value & v)
}
-void EvalState::callFunction(Value & fun, size_t nrArgs, Value * * args, Value & vRes, const Pos & pos)
+void EvalState::callFunction(Value & fun, size_t nrArgs, Value * * args, Value & vRes, const PosIdx pos)
{
- auto trace = evalSettings.traceFunctionCalls ? std::make_unique<FunctionCallTrace>(pos) : nullptr;
+ auto trace = evalSettings.traceFunctionCalls
+ ? std::make_unique<FunctionCallTrace>(positions[pos])
+ : nullptr;
forceValue(fun, pos);
@@ -1341,7 +1589,7 @@ void EvalState::callFunction(Value & fun, size_t nrArgs, Value * * args, Value &
ExprLambda & lambda(*vCur.lambda.fun);
auto size =
- (lambda.arg.empty() ? 0 : 1) +
+ (!lambda.arg ? 0 : 1) +
(lambda.hasFormals() ? lambda.formals->formals.size() : 0);
Env & env2(allocEnv(size));
env2.up = vCur.lambda.env;
@@ -1350,11 +1598,10 @@ void EvalState::callFunction(Value & fun, size_t nrArgs, Value * * args, Value &
if (!lambda.hasFormals())
env2.values[displ++] = args[0];
-
else {
forceAttrs(*args[0], pos);
- if (!lambda.arg.empty())
+ if (lambda.arg)
env2.values[displ++] = args[0];
/* For each formal argument, get the actual argument. If
@@ -1365,7 +1612,7 @@ void EvalState::callFunction(Value & fun, size_t nrArgs, Value * * args, Value &
auto j = args[0]->attrs->get(i.name);
if (!j) {
if (!i.def) throwTypeError(pos, "%1% called without required argument '%2%'",
- lambda, i.name);
+ lambda, i.name, *fun.lambda.env, lambda);
env2.values[displ++] = i.def->maybeThunk(*this, env2);
} else {
attrsUsed++;
@@ -1379,8 +1626,16 @@ void EvalState::callFunction(Value & fun, size_t nrArgs, Value * * args, Value &
/* Nope, so show the first unexpected argument to the
user. */
for (auto & i : *args[0]->attrs)
- if (!lambda.formals->has(i.name))
- throwTypeError(pos, "%1% called with unexpected argument '%2%'", lambda, i.name);
+ if (!lambda.formals->has(i.name)) {
+ std::set<std::string> formalNames;
+ for (auto & formal : lambda.formals->formals)
+ formalNames.insert(symbols[formal.name]);
+ throwTypeError(
+ pos,
+ Suggestions::bestMatches(formalNames, symbols[i.name]),
+ "%1% called with unexpected argument '%2%'",
+ lambda, i.name, *fun.lambda.env, lambda);
+ }
abort(); // can't happen
}
}
@@ -1390,12 +1645,21 @@ void EvalState::callFunction(Value & fun, size_t nrArgs, Value * * args, Value &
/* Evaluate the body. */
try {
+ auto dts = debugRepl
+ ? makeDebugTraceStacker(
+ *this, *lambda.body, env2, positions[lambda.pos],
+ "while evaluating %s",
+ lambda.name
+ ? concatStrings("'", symbols[lambda.name], "'")
+ : "anonymous lambda")
+ : nullptr;
+
lambda.body->eval(*this, env2, vCur);
} catch (Error & e) {
if (loggerSettings.showTrace.get()) {
addErrorTrace(e, lambda.pos, "while evaluating %s",
- (lambda.name.set()
- ? "'" + (const std::string &) lambda.name + "'"
+ (lambda.name
+ ? concatStrings("'", symbols[lambda.name], "'")
: "anonymous lambda"));
addErrorTrace(e, pos, "from call site%s", "");
}
@@ -1544,8 +1808,8 @@ void EvalState::autoCallFunction(Bindings & args, Value & fun, Value & res)
Nix attempted to evaluate a function as a top level expression; in
this case it must have its arguments supplied either by default
values, or passed explicitly with '--arg' or '--argstr'. See
-https://nixos.org/manual/nix/stable/#ss-functions.)", i.name);
-
+https://nixos.org/manual/nix/stable/expressions/language-constructs.html#functions.)", symbols[i.name],
+ *fun.lambda.env, *fun.lambda.fun);
}
}
}
@@ -1576,8 +1840,8 @@ void ExprAssert::eval(EvalState & state, Env & env, Value & v)
{
if (!state.evalBool(env, cond, pos)) {
std::ostringstream out;
- cond->show(out);
- throwAssertionError(pos, "assertion '%1%' failed", out.str());
+ cond->show(state.symbols, out);
+ state.throwAssertionError(pos, "assertion '%1%' failed", out.str(), env, *this);
}
body->eval(state, env, v);
}
@@ -1670,7 +1934,7 @@ void ExprOpConcatLists::eval(EvalState & state, Env & env, Value & v)
}
-void EvalState::concatLists(Value & v, size_t nrLists, Value * * lists, const Pos & pos)
+void EvalState::concatLists(Value & v, size_t nrLists, Value * * lists, const PosIdx pos)
{
nrListConcats++;
@@ -1754,14 +2018,14 @@ void ExprConcatStrings::eval(EvalState & state, Env & env, Value & v)
nf = n;
nf += vTmp.fpoint;
} else
- throwEvalError(i_pos, "cannot add %1% to an integer", showType(vTmp));
+ state.throwEvalError(i_pos, "cannot add %1% to an integer", showType(vTmp), env, *this);
} else if (firstType == nFloat) {
if (vTmp.type() == nInt) {
nf += vTmp.integer;
} else if (vTmp.type() == nFloat) {
nf += vTmp.fpoint;
} else
- throwEvalError(i_pos, "cannot add %1% to a float", showType(vTmp));
+ state.throwEvalError(i_pos, "cannot add %1% to a float", showType(vTmp), env, *this);
} else {
if (s.empty()) s.reserve(es->size());
/* skip canonization of first path, which would only be not
@@ -1781,7 +2045,7 @@ void ExprConcatStrings::eval(EvalState & state, Env & env, Value & v)
v.mkFloat(nf);
else if (firstType == nPath) {
if (!context.empty())
- throwEvalError(pos, "a string that refers to a store path cannot be appended to a path");
+ state.throwEvalError(pos, "a string that refers to a store path cannot be appended to a path", env, *this);
v.mkPath(canonPath(str()));
} else
v.mkStringMove(c_str(), context);
@@ -1790,7 +2054,7 @@ void ExprConcatStrings::eval(EvalState & state, Env & env, Value & v)
void ExprPos::eval(EvalState & state, Env & env, Value & v)
{
- state.mkPos(v, ptr(&pos));
+ state.mkPos(v, pos);
}
@@ -1808,9 +2072,15 @@ void EvalState::forceValueDeep(Value & v)
if (v.type() == nAttrs) {
for (auto & i : *v.attrs)
try {
+ // If the value is a thunk, we're evaling. Otherwise no trace necessary.
+ auto dts = debugRepl && i.value->isThunk()
+ ? makeDebugTraceStacker(*this, *i.value->thunk.expr, *i.value->thunk.env, positions[i.pos],
+ "while evaluating the attribute '%1%'", symbols[i.name])
+ : nullptr;
+
recurse(*i.value);
} catch (Error & e) {
- addErrorTrace(e, *i.pos, "while evaluating the attribute '%1%'", i.name);
+ addErrorTrace(e, i.pos, "while evaluating the attribute '%1%'", symbols[i.name]);
throw;
}
}
@@ -1825,16 +2095,17 @@ void EvalState::forceValueDeep(Value & v)
}
-NixInt EvalState::forceInt(Value & v, const Pos & pos)
+NixInt EvalState::forceInt(Value & v, const PosIdx pos)
{
forceValue(v, pos);
if (v.type() != nInt)
throwTypeError(pos, "value is %1% while an integer was expected", v);
+
return v.integer;
}
-NixFloat EvalState::forceFloat(Value & v, const Pos & pos)
+NixFloat EvalState::forceFloat(Value & v, const PosIdx pos)
{
forceValue(v, pos);
if (v.type() == nInt)
@@ -1845,7 +2116,7 @@ NixFloat EvalState::forceFloat(Value & v, const Pos & pos)
}
-bool EvalState::forceBool(Value & v, const Pos & pos)
+bool EvalState::forceBool(Value & v, const PosIdx pos)
{
forceValue(v, pos);
if (v.type() != nBool)
@@ -1860,7 +2131,7 @@ bool EvalState::isFunctor(Value & fun)
}
-void EvalState::forceFunction(Value & v, const Pos & pos)
+void EvalState::forceFunction(Value & v, const PosIdx pos)
{
forceValue(v, pos);
if (v.type() != nFunction && !isFunctor(v))
@@ -1868,14 +2139,11 @@ void EvalState::forceFunction(Value & v, const Pos & pos)
}
-std::string_view EvalState::forceString(Value & v, const Pos & pos)
+std::string_view EvalState::forceString(Value & v, const PosIdx pos)
{
forceValue(v, pos);
if (v.type() != nString) {
- if (pos)
- throwTypeError(pos, "value is %1% while a string was expected", v);
- else
- throwTypeError("value is %1% while a string was expected", v);
+ throwTypeError(pos, "value is %1% while a string was expected", v);
}
return v.string.s;
}
@@ -1883,13 +2151,22 @@ std::string_view EvalState::forceString(Value & v, const Pos & pos)
/* Decode a context string ‘!<name>!<path>’ into a pair <path,
name>. */
-std::pair<std::string, std::string> decodeContext(std::string_view s)
+NixStringContextElem decodeContext(const Store & store, std::string_view s)
{
if (s.at(0) == '!') {
size_t index = s.find("!", 1);
- return {std::string(s.substr(index + 1)), std::string(s.substr(1, index - 1))};
+ return {
+ store.parseStorePath(s.substr(index + 1)),
+ std::string(s.substr(1, index - 1)),
+ };
} else
- return {s.at(0) == '/' ? std::string(s) : std::string(s.substr(1)), ""};
+ return {
+ store.parseStorePath(
+ s.at(0) == '/'
+ ? s
+ : s.substr(1)),
+ "",
+ };
}
@@ -1901,18 +2178,18 @@ void copyContext(const Value & v, PathSet & context)
}
-std::vector<std::pair<Path, std::string>> Value::getContext()
+NixStringContext Value::getContext(const Store & store)
{
- std::vector<std::pair<Path, std::string>> res;
+ NixStringContext res;
assert(internalType == tString);
if (string.context)
for (const char * * p = string.context; *p; ++p)
- res.push_back(decodeContext(*p));
+ res.push_back(decodeContext(store, *p));
return res;
}
-std::string_view EvalState::forceString(Value & v, PathSet & context, const Pos & pos)
+std::string_view EvalState::forceString(Value & v, PathSet & context, const PosIdx pos)
{
auto s = forceString(v, pos);
copyContext(v, context);
@@ -1920,7 +2197,7 @@ std::string_view EvalState::forceString(Value & v, PathSet & context, const Pos
}
-std::string_view EvalState::forceStringNoCtx(Value & v, const Pos & pos)
+std::string_view EvalState::forceStringNoCtx(Value & v, const PosIdx pos)
{
auto s = forceString(v, pos);
if (v.string.context) {
@@ -1940,13 +2217,13 @@ bool EvalState::isDerivation(Value & v)
if (v.type() != nAttrs) return false;
Bindings::iterator i = v.attrs->find(sType);
if (i == v.attrs->end()) return false;
- forceValue(*i->value, *i->pos);
+ forceValue(*i->value, i->pos);
if (i->value->type() != nString) return false;
return strcmp(i->value->string.s, "derivation") == 0;
}
-std::optional<std::string> EvalState::tryAttrsToString(const Pos & pos, Value & v,
+std::optional<std::string> EvalState::tryAttrsToString(const PosIdx pos, Value & v,
PathSet & context, bool coerceMore, bool copyToStore)
{
auto i = v.attrs->find(sToString);
@@ -1959,7 +2236,7 @@ std::optional<std::string> EvalState::tryAttrsToString(const Pos & pos, Value &
return {};
}
-BackedStringView EvalState::coerceToString(const Pos & pos, Value & v, PathSet & context,
+BackedStringView EvalState::coerceToString(const PosIdx pos, Value & v, PathSet & context,
bool coerceMore, bool copyToStore, bool canonicalizePath)
{
forceValue(v, pos);
@@ -1983,15 +2260,15 @@ BackedStringView EvalState::coerceToString(const Pos & pos, Value & v, PathSet &
if (maybeString)
return std::move(*maybeString);
auto i = v.attrs->find(sOutPath);
- if (i == v.attrs->end()) throwTypeError(pos, "cannot coerce a set to a string");
+ if (i == v.attrs->end())
+ throwTypeError(pos, "cannot coerce a set to a string");
return coerceToString(pos, *i->value, context, coerceMore, copyToStore);
}
if (v.type() == nExternal)
- return v.external->coerceToString(pos, context, coerceMore, copyToStore);
+ return v.external->coerceToString(positions[pos], context, coerceMore, copyToStore);
if (coerceMore) {
-
/* Note that `false' is represented as an empty string for
shell scripting convenience, just like `null'. */
if (v.type() == nBool && v.boolean) return "1";
@@ -2041,7 +2318,7 @@ std::string EvalState::copyPathToStore(PathSet & context, const Path & path)
}
-Path EvalState::coerceToPath(const Pos & pos, Value & v, PathSet & context)
+Path EvalState::coerceToPath(const PosIdx pos, Value & v, PathSet & context)
{
auto path = coerceToString(pos, v, context, false, false).toOwned();
if (path == "" || path[0] != '/')
@@ -2050,6 +2327,18 @@ Path EvalState::coerceToPath(const Pos & pos, Value & v, PathSet & context)
}
+StorePath EvalState::coerceToStorePath(const PosIdx pos, Value & v, PathSet & context)
+{
+ auto path = coerceToString(pos, v, context, false, false).toOwned();
+ if (auto storePath = store->maybeParseStorePath(path))
+ return *storePath;
+ throw EvalError({
+ .msg = hintfmt("path '%1%' is not in the Nix store", path),
+ .errPos = positions[pos]
+ });
+}
+
+
bool EvalState::eqValues(Value & v1, Value & v2)
{
forceValue(v1, noPos);
@@ -2124,7 +2413,9 @@ bool EvalState::eqValues(Value & v1, Value & v2)
return v1.fpoint == v2.fpoint;
default:
- throwEvalError("cannot compare %1% with %2%", showType(v1), showType(v2));
+ throwEvalError("cannot compare %1% with %2%",
+ showType(v1),
+ showType(v2));
}
}
@@ -2210,28 +2501,28 @@ void EvalState::printStats()
}
{
auto list = topObj.list("functions");
- for (auto & i : functionCalls) {
+ for (auto & [fun, count] : functionCalls) {
auto obj = list.object();
- if (i.first->name.set())
- obj.attr("name", (const std::string &) i.first->name);
+ if (fun->name)
+ obj.attr("name", (std::string_view) symbols[fun->name]);
else
obj.attr("name", nullptr);
- if (i.first->pos) {
- obj.attr("file", (const std::string &) i.first->pos.file);
- obj.attr("line", i.first->pos.line);
- obj.attr("column", i.first->pos.column);
+ if (auto pos = positions[fun->pos]) {
+ obj.attr("file", (std::string_view) pos.file);
+ obj.attr("line", pos.line);
+ obj.attr("column", pos.column);
}
- obj.attr("count", i.second);
+ obj.attr("count", count);
}
}
{
auto list = topObj.list("attributes");
for (auto & i : attrSelects) {
auto obj = list.object();
- if (i.first) {
- obj.attr("file", (const std::string &) i.first.file);
- obj.attr("line", i.first.line);
- obj.attr("column", i.first.column);
+ if (auto pos = positions[i.first]) {
+ obj.attr("file", (const std::string &) pos.file);
+ obj.attr("line", pos.line);
+ obj.attr("column", pos.column);
}
obj.attr("count", i.second);
}
diff --git a/src/libexpr/eval.hh b/src/libexpr/eval.hh
index 1f0e97b2e..f07f15d43 100644
--- a/src/libexpr/eval.hh
+++ b/src/libexpr/eval.hh
@@ -13,7 +13,6 @@
#include <unordered_map>
#include <mutex>
-
namespace nix {
@@ -23,18 +22,22 @@ class StorePath;
enum RepairFlag : bool;
-typedef void (* PrimOpFun) (EvalState & state, const Pos & pos, Value * * args, Value & v);
-
+typedef void (* PrimOpFun) (EvalState & state, const PosIdx pos, Value * * args, Value & v);
struct PrimOp
{
PrimOpFun fun;
size_t arity;
- Symbol name;
+ std::string name;
std::vector<std::string> args;
const char * doc = nullptr;
};
+#if HAVE_BOEHMGC
+ typedef std::map<std::string, Value *, std::less<std::string>, traceable_allocator<std::pair<const std::string, Value *> > > ValMap;
+#else
+ typedef std::map<std::string, Value *> ValMap;
+#endif
struct Env
{
@@ -44,6 +47,10 @@ struct Env
Value * values[0];
};
+void printEnvBindings(const EvalState &es, const Expr & expr, const Env & env);
+void printEnvBindings(const SymbolTable & st, const StaticEnv & se, const Env & env, int lvl = 0);
+
+std::unique_ptr<ValMap> mapStaticEnvBindings(const SymbolTable & st, const StaticEnv & se, const Env & env);
void copyContext(const Value & v, PathSet & context);
@@ -53,7 +60,9 @@ void copyContext(const Value & v, PathSet & context);
typedef std::map<Path, StorePath> SrcToStore;
-std::ostream & operator << (std::ostream & str, const Value & v);
+std::ostream & printValue(const EvalState & state, std::ostream & str, const Value & v);
+std::string printValue(const EvalState & state, const Value & v);
+std::ostream & operator << (std::ostream & os, const ValueType t);
typedef std::pair<std::string, std::string> SearchPathElem;
@@ -68,21 +77,34 @@ struct RegexCache;
std::shared_ptr<RegexCache> makeRegexCache();
+struct DebugTrace {
+ std::optional<ErrPos> pos;
+ const Expr & expr;
+ const Env & env;
+ hintformat hint;
+ bool isError;
+};
+
+void debugError(Error * e, Env & env, Expr & expr);
-class EvalState
+class EvalState : public std::enable_shared_from_this<EvalState>
{
public:
SymbolTable symbols;
+ PosTable positions;
+
+ static inline std::string derivationNixPath = "//builtin/derivation.nix";
const Symbol sWith, sOutPath, sDrvPath, sType, sMeta, sName, sValue,
sSystem, sOverrides, sOutputs, sOutputName, sIgnoreNulls,
sFile, sLine, sColumn, sFunctor, sToString,
sRight, sWrong, sStructuredAttrs, sBuilder, sArgs,
- sContentAddressed,
+ sContentAddressed, sImpure,
sOutputHash, sOutputHashAlgo, sOutputHashMode,
sRecurseForDerivations,
sDescription, sSelf, sEpsilon, sStartSet, sOperator, sKey, sPath,
- sPrefix;
+ sPrefix,
+ sOutputSpecified;
Symbol sDerivationNix;
/* If set, force copying files to the Nix store even if they
@@ -104,12 +126,56 @@ public:
RootValue vCallFlake = nullptr;
RootValue vImportedDrvToDerivation = nullptr;
+ /* Debugger */
+ void (* debugRepl)(ref<EvalState> es, const ValMap & extraEnv);
+ bool debugStop;
+ bool debugQuit;
+ int trylevel;
+ std::list<DebugTrace> debugTraces;
+ std::map<const Expr*, const std::shared_ptr<const StaticEnv>> exprEnvs;
+ const std::shared_ptr<const StaticEnv> getStaticEnv(const Expr & expr) const
+ {
+ auto i = exprEnvs.find(&expr);
+ if (i != exprEnvs.end())
+ return i->second;
+ else
+ return std::shared_ptr<const StaticEnv>();;
+ }
+
+ void runDebugRepl(const Error * error, const Env & env, const Expr & expr);
+
+ template<class E>
+ [[gnu::noinline, gnu::noreturn]]
+ void debugThrow(E && error, const Env & env, const Expr & expr)
+ {
+ if (debugRepl)
+ runDebugRepl(&error, env, expr);
+
+ throw std::move(error);
+ }
+
+ template<class E>
+ [[gnu::noinline, gnu::noreturn]]
+ void debugThrowLastTrace(E && e)
+ {
+ // Call this in the situation where Expr and Env are inaccessible.
+ // The debugger will start in the last context that's in the
+ // DebugTrace stack.
+ if (debugRepl && !debugTraces.empty()) {
+ const DebugTrace & last = debugTraces.front();
+ runDebugRepl(&e, last.env, last.expr);
+ }
+
+ throw std::move(e);
+ }
+
+
private:
SrcToStore srcToStore;
/* A cache from path names to parse trees. */
#if HAVE_BOEHMGC
- typedef std::map<Path, Expr *, std::less<Path>, traceable_allocator<std::pair<const Path, Expr *> > > FileParseCache;
+ typedef std::map<Path, Expr *, std::less<Path>, traceable_allocator<std::pair<const Path, Expr *>>> FileParseCache;
#else
typedef std::map<Path, Expr *> FileParseCache;
#endif
@@ -117,7 +183,7 @@ private:
/* A cache from path names to values. */
#if HAVE_BOEHMGC
- typedef std::map<Path, Value, std::less<Path>, traceable_allocator<std::pair<const Path, Value> > > FileEvalCache;
+ typedef std::map<Path, Value, std::less<Path>, traceable_allocator<std::pair<const Path, Value>>> FileEvalCache;
#else
typedef std::map<Path, Value> FileEvalCache;
#endif
@@ -133,9 +199,14 @@ private:
/* Cache used by prim_match(). */
std::shared_ptr<RegexCache> regexCache;
+#if HAVE_BOEHMGC
/* Allocation cache for GC'd Value objects. */
std::shared_ptr<void *> valueAllocCache;
+ /* Allocation cache for size-1 Env objects. */
+ std::shared_ptr<void *> env1AllocCache;
+#endif
+
public:
EvalState(
@@ -144,12 +215,6 @@ public:
std::shared_ptr<Store> buildStore = nullptr);
~EvalState();
- void requireExperimentalFeatureOnEvaluation(
- const ExperimentalFeature &,
- const std::string_view fName,
- const Pos & pos
- );
-
void addToSearchPath(const std::string & s);
SearchPath getSearchPath() { return searchPath; }
@@ -161,6 +226,9 @@ public:
the real store path if `store` is a chroot store. */
void allowPath(const StorePath & storePath);
+ /* Allow access to a store path and return it as a string. */
+ void allowAndSetStorePathString(const StorePath & storePath, Value & v);
+
/* Check whether access to a path is allowed and throw an error if
not. Otherwise return the canonicalised path. */
Path checkSourcePath(const Path & path);
@@ -178,10 +246,10 @@ public:
/* Parse a Nix expression from the specified file. */
Expr * parseExprFromFile(const Path & path);
- Expr * parseExprFromFile(const Path & path, StaticEnv & staticEnv);
+ Expr * parseExprFromFile(const Path & path, std::shared_ptr<StaticEnv> & staticEnv);
/* Parse a Nix expression from the specified string. */
- Expr * parseExprFromString(std::string s, const Path & basePath, StaticEnv & staticEnv);
+ Expr * parseExprFromString(std::string s, const Path & basePath, std::shared_ptr<StaticEnv> & staticEnv);
Expr * parseExprFromString(std::string s, const Path & basePath);
Expr * parseStdin();
@@ -191,7 +259,7 @@ public:
trivial (i.e. doesn't require arbitrary computation). */
void evalFile(const Path & path, Value & v, bool mustBeTrivial = false);
- /* Like `cacheFile`, but with an already parsed expression. */
+ /* Like `evalFile`, but with an already parsed expression. */
void cacheFile(
const Path & path,
const Path & resolvedPath,
@@ -203,7 +271,7 @@ public:
/* Look up a file in the search path. */
Path findFile(const std::string_view path);
- Path findFile(SearchPath & searchPath, const std::string_view path, const Pos & pos = noPos);
+ Path findFile(SearchPath & searchPath, const std::string_view path, const PosIdx pos = noPos);
/* If the specified search path element is a URI, download it. */
std::pair<bool, std::string> resolveSearchPathElem(const SearchPathElem & elem);
@@ -215,14 +283,14 @@ public:
/* Evaluation the expression, then verify that it has the expected
type. */
inline bool evalBool(Env & env, Expr * e);
- inline bool evalBool(Env & env, Expr * e, const Pos & pos);
+ inline bool evalBool(Env & env, Expr * e, const PosIdx pos);
inline void evalAttrs(Env & env, Expr * e, Value & v);
/* If `v' is a thunk, enter it and overwrite `v' with the result
of the evaluation of the thunk. If `v' is a delayed function
application, call the function and overwrite `v' with the
result. Otherwise, this is a no-op. */
- inline void forceValue(Value & v, const Pos & pos);
+ inline void forceValue(Value & v, const PosIdx pos);
template <typename Callable>
inline void forceValue(Value & v, Callable getPos);
@@ -232,33 +300,103 @@ public:
void forceValueDeep(Value & v);
/* Force `v', and then verify that it has the expected type. */
- NixInt forceInt(Value & v, const Pos & pos);
- NixFloat forceFloat(Value & v, const Pos & pos);
- bool forceBool(Value & v, const Pos & pos);
+ NixInt forceInt(Value & v, const PosIdx pos);
+ NixFloat forceFloat(Value & v, const PosIdx pos);
+ bool forceBool(Value & v, const PosIdx pos);
- void forceAttrs(Value & v, const Pos & pos);
+ void forceAttrs(Value & v, const PosIdx pos);
template <typename Callable>
inline void forceAttrs(Value & v, Callable getPos);
- inline void forceList(Value & v, const Pos & pos);
- void forceFunction(Value & v, const Pos & pos); // either lambda or primop
- std::string_view forceString(Value & v, const Pos & pos = noPos);
- std::string_view forceString(Value & v, PathSet & context, const Pos & pos = noPos);
- std::string_view forceStringNoCtx(Value & v, const Pos & pos = noPos);
+ inline void forceList(Value & v, const PosIdx pos);
+ void forceFunction(Value & v, const PosIdx pos); // either lambda or primop
+ std::string_view forceString(Value & v, const PosIdx pos = noPos);
+ std::string_view forceString(Value & v, PathSet & context, const PosIdx pos = noPos);
+ std::string_view forceStringNoCtx(Value & v, const PosIdx pos = noPos);
+
+ [[gnu::noinline, gnu::noreturn]]
+ void throwEvalError(const PosIdx pos, const char * s);
+ [[gnu::noinline, gnu::noreturn]]
+ void throwEvalError(const PosIdx pos, const char * s,
+ Env & env, Expr & expr);
+ [[gnu::noinline, gnu::noreturn]]
+ void throwEvalError(const char * s, const std::string & s2);
+ [[gnu::noinline, gnu::noreturn]]
+ void throwEvalError(const PosIdx pos, const char * s, const std::string & s2);
+ [[gnu::noinline, gnu::noreturn]]
+ void throwEvalError(const char * s, const std::string & s2,
+ Env & env, Expr & expr);
+ [[gnu::noinline, gnu::noreturn]]
+ void throwEvalError(const PosIdx pos, const char * s, const std::string & s2,
+ Env & env, Expr & expr);
+ [[gnu::noinline, gnu::noreturn]]
+ void throwEvalError(const char * s, const std::string & s2, const std::string & s3,
+ Env & env, Expr & expr);
+ [[gnu::noinline, gnu::noreturn]]
+ void throwEvalError(const PosIdx pos, const char * s, const std::string & s2, const std::string & s3,
+ Env & env, Expr & expr);
+ [[gnu::noinline, gnu::noreturn]]
+ void throwEvalError(const PosIdx pos, const char * s, const std::string & s2, const std::string & s3);
+ [[gnu::noinline, gnu::noreturn]]
+ void throwEvalError(const char * s, const std::string & s2, const std::string & s3);
+ [[gnu::noinline, gnu::noreturn]]
+ void throwEvalError(const PosIdx pos, const Suggestions & suggestions, const char * s, const std::string & s2,
+ Env & env, Expr & expr);
+ [[gnu::noinline, gnu::noreturn]]
+ void throwEvalError(const PosIdx p1, const char * s, const Symbol sym, const PosIdx p2,
+ Env & env, Expr & expr);
+
+ [[gnu::noinline, gnu::noreturn]]
+ void throwTypeError(const PosIdx pos, const char * s, const Value & v);
+ [[gnu::noinline, gnu::noreturn]]
+ void throwTypeError(const PosIdx pos, const char * s, const Value & v,
+ Env & env, Expr & expr);
+ [[gnu::noinline, gnu::noreturn]]
+ void throwTypeError(const PosIdx pos, const char * s);
+ [[gnu::noinline, gnu::noreturn]]
+ void throwTypeError(const PosIdx pos, const char * s,
+ Env & env, Expr & expr);
+ [[gnu::noinline, gnu::noreturn]]
+ void throwTypeError(const PosIdx pos, const char * s, const ExprLambda & fun, const Symbol s2,
+ Env & env, Expr & expr);
+ [[gnu::noinline, gnu::noreturn]]
+ void throwTypeError(const PosIdx pos, const Suggestions & suggestions, const char * s, const ExprLambda & fun, const Symbol s2,
+ Env & env, Expr & expr);
+ [[gnu::noinline, gnu::noreturn]]
+ void throwTypeError(const char * s, const Value & v,
+ Env & env, Expr & expr);
+
+ [[gnu::noinline, gnu::noreturn]]
+ void throwAssertionError(const PosIdx pos, const char * s, const std::string & s1,
+ Env & env, Expr & expr);
+
+ [[gnu::noinline, gnu::noreturn]]
+ void throwUndefinedVarError(const PosIdx pos, const char * s, const std::string & s1,
+ Env & env, Expr & expr);
+
+ [[gnu::noinline, gnu::noreturn]]
+ void throwMissingArgumentError(const PosIdx pos, const char * s, const std::string & s1,
+ Env & env, Expr & expr);
+
+ [[gnu::noinline]]
+ void addErrorTrace(Error & e, const char * s, const std::string & s2) const;
+ [[gnu::noinline]]
+ void addErrorTrace(Error & e, const PosIdx pos, const char * s, const std::string & s2) const;
+public:
/* Return true iff the value `v' denotes a derivation (i.e. a
set with attribute `type = "derivation"'). */
bool isDerivation(Value & v);
- std::optional<std::string> tryAttrsToString(const Pos & pos, Value & v,
+ std::optional<std::string> tryAttrsToString(const PosIdx pos, Value & v,
PathSet & context, bool coerceMore = false, bool copyToStore = true);
/* String coercion. Converts strings, paths and derivations to a
string. If `coerceMore' is set, also converts nulls, integers,
booleans and lists to a string. If `copyToStore' is set,
referenced paths are copied to the Nix store as a side effect. */
- BackedStringView coerceToString(const Pos & pos, Value & v, PathSet & context,
+ BackedStringView coerceToString(const PosIdx pos, Value & v, PathSet & context,
bool coerceMore = false, bool copyToStore = true,
bool canonicalizePath = true);
@@ -267,7 +405,10 @@ public:
/* Path coercion. Converts strings, paths and derivations to a
path. The result is guaranteed to be a canonicalised, absolute
path. Nothing is copied to the store. */
- Path coerceToPath(const Pos & pos, Value & v, PathSet & context);
+ Path coerceToPath(const PosIdx pos, Value & v, PathSet & context);
+
+ /* Like coerceToPath, but the result must be a store path. */
+ StorePath coerceToStorePath(const PosIdx pos, Value & v, PathSet & context);
public:
@@ -276,7 +417,7 @@ public:
Env & baseEnv;
/* The same, but used during parsing to resolve variables. */
- StaticEnv staticBaseEnv; // !!! should be private
+ std::shared_ptr<StaticEnv> staticBaseEnv; // !!! should be private
private:
@@ -300,7 +441,7 @@ public:
struct Doc
{
Pos pos;
- std::optional<Symbol> name;
+ std::optional<std::string> name;
size_t arity;
std::vector<std::string> args;
const char * doc;
@@ -317,7 +458,7 @@ private:
friend struct ExprLet;
Expr * parse(char * text, size_t length, FileOrigin origin, const PathView path,
- const PathView basePath, StaticEnv & staticEnv);
+ const PathView basePath, std::shared_ptr<StaticEnv> & staticEnv);
public:
@@ -328,9 +469,9 @@ public:
bool isFunctor(Value & fun);
// FIXME: use std::span
- void callFunction(Value & fun, size_t nrArgs, Value * * args, Value & vRes, const Pos & pos);
+ void callFunction(Value & fun, size_t nrArgs, Value * * args, Value & vRes, const PosIdx pos);
- void callFunction(Value & fun, Value & arg, Value & vRes, const Pos & pos)
+ void callFunction(Value & fun, Value & arg, Value & vRes, const PosIdx pos)
{
Value * args[] = {&arg};
callFunction(fun, 1, args, vRes, pos);
@@ -341,10 +482,10 @@ public:
void autoCallFunction(Bindings & args, Value & fun, Value & res);
/* Allocation primitives. */
- Value * allocValue();
- Env & allocEnv(size_t size);
+ inline Value * allocValue();
+ inline Env & allocEnv(size_t size);
- Value * allocAttr(Value & vAttrs, const Symbol & name);
+ Value * allocAttr(Value & vAttrs, Symbol name);
Value * allocAttr(Value & vAttrs, std::string_view name);
Bindings * allocBindings(size_t capacity);
@@ -356,9 +497,9 @@ public:
void mkList(Value & v, size_t length);
void mkThunk_(Value & v, Expr * expr);
- void mkPos(Value & v, ptr<Pos> pos);
+ void mkPos(Value & v, PosIdx pos);
- void concatLists(Value & v, size_t nrLists, Value * * lists, const Pos & pos);
+ void concatLists(Value & v, size_t nrLists, Value * * lists, const PosIdx pos);
/* Print statistics. */
void printStats();
@@ -386,7 +527,7 @@ private:
bool countCalls;
- typedef std::map<Symbol, size_t> PrimOpCalls;
+ typedef std::map<std::string, size_t> PrimOpCalls;
PrimOpCalls primOpCalls;
typedef std::map<ExprLambda *, size_t> FunctionCalls;
@@ -394,7 +535,7 @@ private:
void incrFunctionCall(ExprLambda * fun);
- typedef std::map<Pos, size_t> AttrSelects;
+ typedef std::map<PosIdx, size_t> AttrSelects;
AttrSelects attrSelects;
friend struct ExprOpUpdate;
@@ -405,13 +546,23 @@ private:
friend struct ExprFloat;
friend struct ExprPath;
friend struct ExprSelect;
- friend void prim_getAttr(EvalState & state, const Pos & pos, Value * * args, Value & v);
- friend void prim_match(EvalState & state, const Pos & pos, Value * * args, Value & v);
- friend void prim_split(EvalState & state, const Pos & pos, Value * * args, Value & v);
+ friend void prim_getAttr(EvalState & state, const PosIdx pos, Value * * args, Value & v);
+ friend void prim_match(EvalState & state, const PosIdx pos, Value * * args, Value & v);
+ friend void prim_split(EvalState & state, const PosIdx pos, Value * * args, Value & v);
friend struct Value;
};
+struct DebugTraceStacker {
+ DebugTraceStacker(EvalState & evalState, DebugTrace t);
+ ~DebugTraceStacker()
+ {
+ // assert(evalState.debugTraces.front() == trace);
+ evalState.debugTraces.pop_front();
+ }
+ EvalState & evalState;
+ DebugTrace trace;
+};
/* Return a string representing the type of the value `v'. */
std::string_view showType(ValueType type);
@@ -419,7 +570,7 @@ std::string showType(const Value & v);
/* Decode a context string ‘!<name>!<path>’ into a pair <path,
name>. */
-std::pair<std::string, std::string> decodeContext(std::string_view s);
+NixStringContextElem decodeContext(const Store & store, std::string_view s);
/* If `path' refers to a directory, then append "/default.nix". */
Path resolveExprPath(Path path);
@@ -496,6 +647,15 @@ struct EvalSettings : Config
Setting<bool> useEvalCache{this, true, "eval-cache",
"Whether to use the flake evaluation cache."};
+
+ Setting<bool> ignoreExceptionsDuringTry{this, false, "ignore-try",
+ R"(
+ If set to true, ignore exceptions inside 'tryEval' calls when evaluating nix expressions in
+ debug mode (using the --debugger flag). By default the debugger will pause on all exceptions.
+ )"};
+
+ Setting<bool> traceVerbose{this, false, "trace-verbose",
+ "Whether `builtins.traceVerbose` should trace its first argument when evaluated."};
};
extern EvalSettings evalSettings;
@@ -503,3 +663,5 @@ extern EvalSettings evalSettings;
static const std::string corepkgsPrefix{"/__corepkgs__/"};
}
+
+#include "eval-inline.hh"
diff --git a/src/libexpr/fetchurl.nix b/src/libexpr/fetchurl.nix
index 02531103b..9d1b61d7f 100644
--- a/src/libexpr/fetchurl.nix
+++ b/src/libexpr/fetchurl.nix
@@ -12,13 +12,13 @@
, executable ? false
, unpack ? false
, name ? baseNameOf (toString url)
+, impure ? false
}:
-derivation {
+derivation ({
builder = "builtin:fetchurl";
# New-style output content requirements.
- inherit outputHashAlgo outputHash;
outputHashMode = if unpack || executable then "recursive" else "flat";
inherit name url executable unpack;
@@ -38,4 +38,6 @@ derivation {
# To make "nix-prefetch-url" work.
urls = [ url ];
-}
+} // (if impure
+ then { __impure = true; }
+ else { inherit outputHashAlgo outputHash; }))
diff --git a/src/libexpr/flake/call-flake.nix b/src/libexpr/flake/call-flake.nix
index 932ac5e90..8061db3df 100644
--- a/src/libexpr/flake/call-flake.nix
+++ b/src/libexpr/flake/call-flake.nix
@@ -43,7 +43,7 @@ let
outputs = flake.outputs (inputs // { self = result; });
- result = outputs // sourceInfo // { inherit inputs; inherit outputs; inherit sourceInfo; };
+ result = outputs // sourceInfo // { inherit inputs; inherit outputs; inherit sourceInfo; _type = "flake"; };
in
if node.flake or true then
assert builtins.isFunction flake.outputs;
diff --git a/src/libexpr/flake/config.cc b/src/libexpr/flake/config.cc
index 7ecd61816..6df95f1f0 100644
--- a/src/libexpr/flake/config.cc
+++ b/src/libexpr/flake/config.cc
@@ -1,5 +1,6 @@
#include "flake.hh"
#include "globals.hh"
+#include "fetch-settings.hh"
#include <nlohmann/json.hpp>
@@ -30,7 +31,7 @@ static void writeTrustedList(const TrustedList & trustedList)
void ConfigFile::apply()
{
- std::set<std::string> whitelist{"bash-prompt", "bash-prompt-suffix", "flake-registry"};
+ std::set<std::string> whitelist{"bash-prompt", "bash-prompt-prefix", "bash-prompt-suffix", "flake-registry"};
for (auto & [name, value] : settings) {
@@ -49,13 +50,11 @@ void ConfigFile::apply()
else
assert(false);
- if (!whitelist.count(baseName)) {
- auto trustedList = readTrustedList();
-
+ if (!whitelist.count(baseName) && !nix::fetchSettings.acceptFlakeConfig) {
bool trusted = false;
- if (nix::settings.acceptFlakeConfig){
- trusted = true;
- } else if (auto saved = get(get(trustedList, name).value_or(std::map<std::string, bool>()), valueS)) {
+ auto trustedList = readTrustedList();
+ auto tlname = get(trustedList, name);
+ if (auto saved = tlname ? get(*tlname, valueS) : nullptr) {
trusted = *saved;
warn("Using saved setting for '%s = %s' from ~/.local/share/nix/trusted-settings.json.", name,valueS);
} else {
@@ -68,9 +67,8 @@ void ConfigFile::apply()
writeTrustedList(trustedList);
}
}
-
if (!trusted) {
- warn("ignoring untrusted flake configuration setting '%s'", name);
+ warn("ignoring untrusted flake configuration setting '%s'.\nPass '%s' to trust it", name, "--accept-flake-config");
continue;
}
}
diff --git a/src/libexpr/flake/flake.cc b/src/libexpr/flake/flake.cc
index ad0881641..119c556ac 100644
--- a/src/libexpr/flake/flake.cc
+++ b/src/libexpr/flake/flake.cc
@@ -6,6 +6,7 @@
#include "store-api.hh"
#include "fetchers.hh"
#include "finally.hh"
+#include "fetch-settings.hh"
namespace nix {
@@ -71,7 +72,7 @@ static std::tuple<fetchers::Tree, FlakeRef, FlakeRef> fetchOrSubstituteTree(
return {std::move(tree), resolvedRef, lockedRef};
}
-static void forceTrivialValue(EvalState & state, Value & value, const Pos & pos)
+static void forceTrivialValue(EvalState & state, Value & value, const PosIdx pos)
{
if (value.isThunk() && value.isTrivial())
state.forceValue(value, pos);
@@ -79,20 +80,20 @@ static void forceTrivialValue(EvalState & state, Value & value, const Pos & pos)
static void expectType(EvalState & state, ValueType type,
- Value & value, const Pos & pos)
+ Value & value, const PosIdx pos)
{
forceTrivialValue(state, value, pos);
if (value.type() != type)
throw Error("expected %s but got %s at %s",
- showType(type), showType(value.type()), pos);
+ showType(type), showType(value.type()), state.positions[pos]);
}
static std::map<FlakeId, FlakeInput> parseFlakeInputs(
- EvalState & state, Value * value, const Pos & pos,
+ EvalState & state, Value * value, const PosIdx pos,
const std::optional<Path> & baseDir, InputPath lockRootPath);
static FlakeInput parseFlakeInput(EvalState & state,
- const std::string & inputName, Value * value, const Pos & pos,
+ const std::string & inputName, Value * value, const PosIdx pos,
const std::optional<Path> & baseDir, InputPath lockRootPath)
{
expectType(state, nAttrs, *value, pos);
@@ -110,37 +111,39 @@ static FlakeInput parseFlakeInput(EvalState & state,
for (nix::Attr attr : *(value->attrs)) {
try {
if (attr.name == sUrl) {
- expectType(state, nString, *attr.value, *attr.pos);
+ expectType(state, nString, *attr.value, attr.pos);
url = attr.value->string.s;
attrs.emplace("url", *url);
} else if (attr.name == sFlake) {
- expectType(state, nBool, *attr.value, *attr.pos);
+ expectType(state, nBool, *attr.value, attr.pos);
input.isFlake = attr.value->boolean;
} else if (attr.name == sInputs) {
- input.overrides = parseFlakeInputs(state, attr.value, *attr.pos, baseDir, lockRootPath);
+ input.overrides = parseFlakeInputs(state, attr.value, attr.pos, baseDir, lockRootPath);
} else if (attr.name == sFollows) {
- expectType(state, nString, *attr.value, *attr.pos);
+ expectType(state, nString, *attr.value, attr.pos);
auto follows(parseInputPath(attr.value->string.s));
follows.insert(follows.begin(), lockRootPath.begin(), lockRootPath.end());
input.follows = follows;
} else {
switch (attr.value->type()) {
case nString:
- attrs.emplace(attr.name, attr.value->string.s);
+ attrs.emplace(state.symbols[attr.name], attr.value->string.s);
break;
case nBool:
- attrs.emplace(attr.name, Explicit<bool> { attr.value->boolean });
+ attrs.emplace(state.symbols[attr.name], Explicit<bool> { attr.value->boolean });
break;
case nInt:
- attrs.emplace(attr.name, (long unsigned int)attr.value->integer);
+ attrs.emplace(state.symbols[attr.name], (long unsigned int)attr.value->integer);
break;
default:
throw TypeError("flake input attribute '%s' is %s while a string, Boolean, or integer is expected",
- attr.name, showType(*attr.value));
+ state.symbols[attr.name], showType(*attr.value));
}
}
} catch (Error & e) {
- e.addTrace(*attr.pos, hintfmt("in flake attribute '%s'", attr.name));
+ e.addTrace(
+ state.positions[attr.pos],
+ hintfmt("in flake attribute '%s'", state.symbols[attr.name]));
throw;
}
}
@@ -149,13 +152,13 @@ static FlakeInput parseFlakeInput(EvalState & state,
try {
input.ref = FlakeRef::fromAttrs(attrs);
} catch (Error & e) {
- e.addTrace(pos, hintfmt("in flake input"));
+ e.addTrace(state.positions[pos], hintfmt("in flake input"));
throw;
}
else {
attrs.erase("url");
if (!attrs.empty())
- throw Error("unexpected flake input attribute '%s', at %s", attrs.begin()->first, pos);
+ throw Error("unexpected flake input attribute '%s', at %s", attrs.begin()->first, state.positions[pos]);
if (url)
input.ref = parseFlakeRef(*url, baseDir, true, input.isFlake);
}
@@ -167,7 +170,7 @@ static FlakeInput parseFlakeInput(EvalState & state,
}
static std::map<FlakeId, FlakeInput> parseFlakeInputs(
- EvalState & state, Value * value, const Pos & pos,
+ EvalState & state, Value * value, const PosIdx pos,
const std::optional<Path> & baseDir, InputPath lockRootPath)
{
std::map<FlakeId, FlakeInput> inputs;
@@ -175,11 +178,11 @@ static std::map<FlakeId, FlakeInput> parseFlakeInputs(
expectType(state, nAttrs, *value, pos);
for (nix::Attr & inputAttr : *(*value).attrs) {
- inputs.emplace(inputAttr.name,
+ inputs.emplace(state.symbols[inputAttr.name],
parseFlakeInput(state,
- inputAttr.name,
+ state.symbols[inputAttr.name],
inputAttr.value,
- *inputAttr.pos,
+ inputAttr.pos,
baseDir,
lockRootPath));
}
@@ -217,28 +220,28 @@ static Flake getFlake(
Value vInfo;
state.evalFile(flakeFile, vInfo, true); // FIXME: symlink attack
- expectType(state, nAttrs, vInfo, Pos(foFile, state.symbols.create(flakeFile), 0, 0));
+ expectType(state, nAttrs, vInfo, state.positions.add({flakeFile, foFile}, 0, 0));
if (auto description = vInfo.attrs->get(state.sDescription)) {
- expectType(state, nString, *description->value, *description->pos);
+ expectType(state, nString, *description->value, description->pos);
flake.description = description->value->string.s;
}
auto sInputs = state.symbols.create("inputs");
if (auto inputs = vInfo.attrs->get(sInputs))
- flake.inputs = parseFlakeInputs(state, inputs->value, *inputs->pos, flakeDir, lockRootPath);
+ flake.inputs = parseFlakeInputs(state, inputs->value, inputs->pos, flakeDir, lockRootPath);
auto sOutputs = state.symbols.create("outputs");
if (auto outputs = vInfo.attrs->get(sOutputs)) {
- expectType(state, nFunction, *outputs->value, *outputs->pos);
+ expectType(state, nFunction, *outputs->value, outputs->pos);
if (outputs->value->isLambda() && outputs->value->lambda.fun->hasFormals()) {
for (auto & formal : outputs->value->lambda.fun->formals->formals) {
if (formal.name != state.sSelf)
- flake.inputs.emplace(formal.name, FlakeInput {
- .ref = parseFlakeRef(formal.name)
+ flake.inputs.emplace(state.symbols[formal.name], FlakeInput {
+ .ref = parseFlakeRef(state.symbols[formal.name])
});
}
}
@@ -249,35 +252,41 @@ static Flake getFlake(
auto sNixConfig = state.symbols.create("nixConfig");
if (auto nixConfig = vInfo.attrs->get(sNixConfig)) {
- expectType(state, nAttrs, *nixConfig->value, *nixConfig->pos);
+ expectType(state, nAttrs, *nixConfig->value, nixConfig->pos);
for (auto & setting : *nixConfig->value->attrs) {
- forceTrivialValue(state, *setting.value, *setting.pos);
+ forceTrivialValue(state, *setting.value, setting.pos);
if (setting.value->type() == nString)
- flake.config.settings.insert({setting.name, std::string(state.forceStringNoCtx(*setting.value, *setting.pos))});
+ flake.config.settings.emplace(
+ state.symbols[setting.name],
+ std::string(state.forceStringNoCtx(*setting.value, setting.pos)));
else if (setting.value->type() == nPath) {
PathSet emptyContext = {};
flake.config.settings.emplace(
- setting.name,
- state.coerceToString(*setting.pos, *setting.value, emptyContext, false, true, true) .toOwned());
+ state.symbols[setting.name],
+ state.coerceToString(setting.pos, *setting.value, emptyContext, false, true, true) .toOwned());
}
else if (setting.value->type() == nInt)
- flake.config.settings.insert({setting.name, state.forceInt(*setting.value, *setting.pos)});
+ flake.config.settings.emplace(
+ state.symbols[setting.name],
+ state.forceInt(*setting.value, setting.pos));
else if (setting.value->type() == nBool)
- flake.config.settings.insert({setting.name, Explicit<bool> { state.forceBool(*setting.value, *setting.pos) }});
+ flake.config.settings.emplace(
+ state.symbols[setting.name],
+ Explicit<bool> { state.forceBool(*setting.value, setting.pos) });
else if (setting.value->type() == nList) {
std::vector<std::string> ss;
for (auto elem : setting.value->listItems()) {
if (elem->type() != nString)
throw TypeError("list element in flake configuration setting '%s' is %s while a string is expected",
- setting.name, showType(*setting.value));
- ss.emplace_back(state.forceStringNoCtx(*elem, *setting.pos));
+ state.symbols[setting.name], showType(*setting.value));
+ ss.emplace_back(state.forceStringNoCtx(*elem, setting.pos));
}
- flake.config.settings.insert({setting.name, ss});
+ flake.config.settings.emplace(state.symbols[setting.name], ss);
}
else
throw TypeError("flake configuration setting '%s' is %s",
- setting.name, showType(*setting.value));
+ state.symbols[setting.name], showType(*setting.value));
}
}
@@ -287,7 +296,7 @@ static Flake getFlake(
attr.name != sOutputs &&
attr.name != sNixConfig)
throw Error("flake '%s' has an unsupported attribute '%s', at %s",
- lockedRef, attr.name, *attr.pos);
+ lockedRef, state.symbols[attr.name], state.positions[attr.pos]);
}
return flake;
@@ -315,7 +324,7 @@ LockedFlake lockFlake(
FlakeCache flakeCache;
- auto useRegistries = lockFlags.useRegistries.value_or(settings.useRegistries);
+ auto useRegistries = lockFlags.useRegistries.value_or(fetchSettings.useRegistries);
auto flake = getFlake(state, topRef, useRegistries, flakeCache);
@@ -332,7 +341,6 @@ LockedFlake lockFlake(
debug("old lock file: %s", oldLockFile);
- // FIXME: check whether all overrides are used.
std::map<InputPath, FlakeInput> overrides;
std::set<InputPath> overridesUsed, updatesUsed;
@@ -375,6 +383,18 @@ LockedFlake lockFlake(
}
}
+ /* Check whether this input has overrides for a
+ non-existent input. */
+ for (auto [inputPath, inputOverride] : overrides) {
+ auto inputPath2(inputPath);
+ auto follow = inputPath2.back();
+ inputPath2.pop_back();
+ if (inputPath2 == inputPathPrefix && !flakeInputs.count(follow))
+ warn(
+ "input '%s' has an override for a non-existent input '%s'",
+ printInputPath(inputPathPrefix), follow);
+ }
+
/* Go over the flake inputs, resolve/fetch them if
necessary (i.e. if they're new or the flakeref changed
from what's in the lock file). */
@@ -463,12 +483,12 @@ LockedFlake lockFlake(
} else if (auto follows = std::get_if<1>(&i.second)) {
if (! trustLock) {
// It is possible that the flake has changed,
- // so we must confirm all the follows that are in the lockfile are also in the flake.
+ // so we must confirm all the follows that are in the lock file are also in the flake.
auto overridePath(inputPath);
overridePath.push_back(i.first);
auto o = overrides.find(overridePath);
// If the override disappeared, we have to refetch the flake,
- // since some of the inputs may not be present in the lockfile.
+ // since some of the inputs may not be present in the lock file.
if (o == overrides.end()) {
mustRefetch = true;
// There's no point populating the rest of the fake inputs,
@@ -504,6 +524,15 @@ LockedFlake lockFlake(
if (!lockFlags.allowMutable && !input.ref->input.isLocked())
throw Error("cannot update flake input '%s' in pure mode", inputPathS);
+ /* Note: in case of an --override-input, we use
+ the *original* ref (input2.ref) for the
+ "original" field, rather than the
+ override. This ensures that the override isn't
+ nuked the next time we update the lock
+ file. That is, overrides are sticky unless you
+ use --no-write-lock-file. */
+ auto ref = input2.ref ? *input2.ref : *input.ref;
+
if (input.isFlake) {
Path localPath = parentPath;
FlakeRef localRef = *input.ref;
@@ -515,15 +544,7 @@ LockedFlake lockFlake(
auto inputFlake = getFlake(state, localRef, useRegistries, flakeCache, inputPath);
- /* Note: in case of an --override-input, we use
- the *original* ref (input2.ref) for the
- "original" field, rather than the
- override. This ensures that the override isn't
- nuked the next time we update the lock
- file. That is, overrides are sticky unless you
- use --no-write-lock-file. */
- auto childNode = std::make_shared<LockedNode>(
- inputFlake.lockedRef, input2.ref ? *input2.ref : *input.ref);
+ auto childNode = std::make_shared<LockedNode>(inputFlake.lockedRef, ref);
node->inputs.insert_or_assign(id, childNode);
@@ -551,7 +572,7 @@ LockedFlake lockFlake(
auto [sourceInfo, resolvedRef, lockedRef] = fetchOrSubstituteTree(
state, *input.ref, useRegistries, flakeCache);
node->inputs.insert_or_assign(id,
- std::make_shared<LockedNode>(lockedRef, *input.ref, false));
+ std::make_shared<LockedNode>(lockedRef, ref, false));
}
}
@@ -591,7 +612,7 @@ LockedFlake lockFlake(
if (lockFlags.writeLockFile) {
if (auto sourcePath = topRef.input.getSourcePath()) {
if (!newLockFile.isImmutable()) {
- if (settings.warnDirty)
+ if (fetchSettings.warnDirty)
warn("will not write lock file of flake '%s' because it has a mutable input", topRef);
} else {
if (!lockFlags.updateLockFile)
@@ -618,7 +639,7 @@ LockedFlake lockFlake(
if (lockFlags.commitLockFile) {
std::string cm;
- cm = settings.commitLockFileSummary.get();
+ cm = fetchSettings.commitLockFileSummary.get();
if (cm == "") {
cm = fmt("%s: %s", relPath, lockFileExists ? "Update" : "Add");
@@ -703,26 +724,48 @@ void callFlake(EvalState & state,
state.callFunction(*vTmp2, *vRootSubdir, vRes, noPos);
}
-static void prim_getFlake(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_getFlake(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
- state.requireExperimentalFeatureOnEvaluation(Xp::Flakes, "builtins.getFlake", pos);
-
std::string flakeRefS(state.forceStringNoCtx(*args[0], pos));
auto flakeRef = parseFlakeRef(flakeRefS, {}, true);
if (evalSettings.pureEval && !flakeRef.input.isLocked())
- throw Error("cannot call 'getFlake' on unlocked flake reference '%s', at %s (use --impure to override)", flakeRefS, pos);
+ throw Error("cannot call 'getFlake' on unlocked flake reference '%s', at %s (use --impure to override)", flakeRefS, state.positions[pos]);
callFlake(state,
lockFlake(state, flakeRef,
LockFlags {
.updateLockFile = false,
- .useRegistries = !evalSettings.pureEval && settings.useRegistries,
+ .writeLockFile = false,
+ .useRegistries = !evalSettings.pureEval && fetchSettings.useRegistries,
.allowMutable = !evalSettings.pureEval,
}),
v);
}
-static RegisterPrimOp r2("__getFlake", 1, prim_getFlake);
+static RegisterPrimOp r2({
+ .name = "__getFlake",
+ .args = {"args"},
+ .doc = R"(
+ Fetch a flake from a flake reference, and return its output attributes and some metadata. For example:
+
+ ```nix
+ (builtins.getFlake "nix/55bc52401966fbffa525c574c14f67b00bc4fb3a").packages.x86_64-linux.nix
+ ```
+
+ Unless impure evaluation is allowed (`--impure`), the flake reference
+ must be "locked", e.g. contain a Git revision or content hash. An
+ example of an unlocked usage is:
+
+ ```nix
+ (builtins.getFlake "github:edolstra/dwarffs").rev
+ ```
+
+ This function is only available if you enable the experimental feature
+ `flakes`.
+ )",
+ .fun = prim_getFlake,
+ .experimentalFeature = Xp::Flakes,
+});
}
diff --git a/src/libexpr/flake/flakeref.cc b/src/libexpr/flake/flakeref.cc
index 930ed9ccd..eede493f8 100644
--- a/src/libexpr/flake/flakeref.cc
+++ b/src/libexpr/flake/flakeref.cc
@@ -98,7 +98,7 @@ std::pair<FlakeRef, std::string> parseFlakeRefWithFragment(
if (std::regex_match(url, match, flakeRegex)) {
auto parsedURL = ParsedURL{
.url = url,
- .base = "flake:" + std::string(match[1]),
+ .base = "flake:" + match.str(1),
.scheme = "flake",
.authority = "",
.path = match[1],
@@ -106,12 +106,12 @@ std::pair<FlakeRef, std::string> parseFlakeRefWithFragment(
return std::make_pair(
FlakeRef(Input::fromURL(parsedURL), ""),
- percentDecode(std::string(match[6])));
+ percentDecode(match.str(6)));
}
else if (std::regex_match(url, match, pathUrlRegex)) {
std::string path = match[1];
- std::string fragment = percentDecode(std::string(match[3]));
+ std::string fragment = percentDecode(match.str(3));
if (baseDir) {
/* Check if 'url' is a path (either absolute or relative
@@ -176,7 +176,7 @@ std::pair<FlakeRef, std::string> parseFlakeRefWithFragment(
parsedURL.query.insert_or_assign("shallow", "1");
return std::make_pair(
- FlakeRef(Input::fromURL(parsedURL), get(parsedURL.query, "dir").value_or("")),
+ FlakeRef(Input::fromURL(parsedURL), getOr(parsedURL.query, "dir", "")),
fragment);
}
@@ -189,7 +189,7 @@ std::pair<FlakeRef, std::string> parseFlakeRefWithFragment(
if (!hasPrefix(path, "/"))
throw BadURL("flake reference '%s' is not an absolute path", url);
auto query = decodeQuery(match[2]);
- path = canonPath(path + "/" + get(query, "dir").value_or(""));
+ path = canonPath(path + "/" + getOr(query, "dir", ""));
}
fetchers::Attrs attrs;
@@ -208,7 +208,7 @@ std::pair<FlakeRef, std::string> parseFlakeRefWithFragment(
input.parent = baseDir;
return std::make_pair(
- FlakeRef(std::move(input), get(parsedURL.query, "dir").value_or("")),
+ FlakeRef(std::move(input), getOr(parsedURL.query, "dir", "")),
fragment);
}
}
@@ -238,4 +238,15 @@ std::pair<fetchers::Tree, FlakeRef> FlakeRef::fetchTree(ref<Store> store) const
return {std::move(tree), FlakeRef(std::move(lockedInput), subdir)};
}
+std::tuple<FlakeRef, std::string, OutputsSpec> parseFlakeRefWithFragmentAndOutputsSpec(
+ const std::string & url,
+ const std::optional<Path> & baseDir,
+ bool allowMissing,
+ bool isFlake)
+{
+ auto [prefix, outputsSpec] = parseOutputsSpec(url);
+ auto [flakeRef, fragment] = parseFlakeRefWithFragment(prefix, baseDir, allowMissing, isFlake);
+ return {std::move(flakeRef), fragment, outputsSpec};
+}
+
}
diff --git a/src/libexpr/flake/flakeref.hh b/src/libexpr/flake/flakeref.hh
index 1fddfd9a0..fe4f67193 100644
--- a/src/libexpr/flake/flakeref.hh
+++ b/src/libexpr/flake/flakeref.hh
@@ -3,6 +3,7 @@
#include "types.hh"
#include "hash.hh"
#include "fetchers.hh"
+#include "path-with-outputs.hh"
#include <variant>
@@ -27,7 +28,7 @@ typedef std::string FlakeId;
* object that fetcher generates (usually via
* FlakeRef::fromAttrs(attrs) or parseFlakeRef(url) calls).
*
- * The actual fetch not have been performed yet (i.e. a FlakeRef may
+ * The actual fetch may not have been performed yet (i.e. a FlakeRef may
* be lazy), but the fetcher can be invoked at any time via the
* FlakeRef to ensure the store is populated with this input.
*/
@@ -79,4 +80,11 @@ std::pair<FlakeRef, std::string> parseFlakeRefWithFragment(
std::optional<std::pair<FlakeRef, std::string>> maybeParseFlakeRefWithFragment(
const std::string & url, const std::optional<Path> & baseDir = {});
+std::tuple<FlakeRef, std::string, OutputsSpec> parseFlakeRefWithFragmentAndOutputsSpec(
+ const std::string & url,
+ const std::optional<Path> & baseDir = {},
+ bool allowMissing = false,
+ bool isFlake = true);
+
+
}
diff --git a/src/libexpr/flake/lockfile.cc b/src/libexpr/flake/lockfile.cc
index 60b52d578..629d2e669 100644
--- a/src/libexpr/flake/lockfile.cc
+++ b/src/libexpr/flake/lockfile.cc
@@ -36,7 +36,7 @@ LockedNode::LockedNode(const nlohmann::json & json)
, isFlake(json.find("flake") != json.end() ? (bool) json["flake"] : true)
{
if (!lockedRef.input.isLocked())
- throw Error("lockfile contains mutable lock '%s'",
+ throw Error("lock file contains mutable lock '%s'",
fetchers::attrsToJSON(lockedRef.input.toAttrs()));
}
diff --git a/src/libexpr/function-trace.hh b/src/libexpr/function-trace.hh
index 472f2045e..e9a2526bd 100644
--- a/src/libexpr/function-trace.hh
+++ b/src/libexpr/function-trace.hh
@@ -8,7 +8,7 @@ namespace nix {
struct FunctionCallTrace
{
- const Pos & pos;
+ const Pos pos;
FunctionCallTrace(const Pos & pos);
~FunctionCallTrace();
};
diff --git a/src/libexpr/get-drvs.cc b/src/libexpr/get-drvs.cc
index 8393e4225..346741dd5 100644
--- a/src/libexpr/get-drvs.cc
+++ b/src/libexpr/get-drvs.cc
@@ -1,6 +1,7 @@
#include "get-drvs.hh"
#include "util.hh"
#include "eval-inline.hh"
+#include "derivations.hh"
#include "store-api.hh"
#include "path-with-outputs.hh"
@@ -22,7 +23,7 @@ DrvInfo::DrvInfo(EvalState & state, ref<Store> store, const std::string & drvPat
{
auto [drvPath, selectedOutputs] = parsePathWithOutputs(*store, drvPathWithOutputs);
- this->drvPath = store->printStorePath(drvPath);
+ this->drvPath = drvPath;
auto drv = store->derivationFromPath(drvPath);
@@ -33,7 +34,7 @@ DrvInfo::DrvInfo(EvalState & state, ref<Store> store, const std::string & drvPat
outputName =
selectedOutputs.empty()
- ? get(drv.env, "outputName").value_or("out")
+ ? getOr(drv.env, "outputName", "out")
: *selectedOutputs.begin();
auto i = drv.outputs.find(outputName);
@@ -41,9 +42,7 @@ DrvInfo::DrvInfo(EvalState & state, ref<Store> store, const std::string & drvPat
throw Error("derivation '%s' does not have output '%s'", store->printStorePath(drvPath), outputName);
auto & [outputName, output] = *i;
- auto optStorePath = output.path(*store, drv.name, outputName);
- if (optStorePath)
- outPath = store->printStorePath(*optStorePath);
+ outPath = {output.path(*store, drv.name, outputName)};
}
@@ -62,30 +61,41 @@ std::string DrvInfo::querySystem() const
{
if (system == "" && attrs) {
auto i = attrs->find(state->sSystem);
- system = i == attrs->end() ? "unknown" : state->forceStringNoCtx(*i->value, *i->pos);
+ system = i == attrs->end() ? "unknown" : state->forceStringNoCtx(*i->value, i->pos);
}
return system;
}
-std::string DrvInfo::queryDrvPath() const
+std::optional<StorePath> DrvInfo::queryDrvPath() const
{
- if (drvPath == "" && attrs) {
+ if (!drvPath && attrs) {
Bindings::iterator i = attrs->find(state->sDrvPath);
PathSet context;
- drvPath = i != attrs->end() ? state->coerceToPath(*i->pos, *i->value, context) : "";
+ if (i == attrs->end())
+ drvPath = {std::nullopt};
+ else
+ drvPath = {state->coerceToStorePath(i->pos, *i->value, context)};
}
- return drvPath;
+ return drvPath.value_or(std::nullopt);
}
-std::string DrvInfo::queryOutPath() const
+StorePath DrvInfo::requireDrvPath() const
+{
+ if (auto drvPath = queryDrvPath())
+ return *drvPath;
+ throw Error("derivation does not contain a 'drvPath' attribute");
+}
+
+
+StorePath DrvInfo::queryOutPath() const
{
if (!outPath && attrs) {
Bindings::iterator i = attrs->find(state->sOutPath);
PathSet context;
if (i != attrs->end())
- outPath = state->coerceToPath(*i->pos, *i->value, context);
+ outPath = state->coerceToStorePath(i->pos, *i->value, context);
}
if (!outPath)
throw UnimplementedError("CA derivations are not yet supported");
@@ -93,48 +103,65 @@ std::string DrvInfo::queryOutPath() const
}
-DrvInfo::Outputs DrvInfo::queryOutputs(bool onlyOutputsToInstall)
+DrvInfo::Outputs DrvInfo::queryOutputs(bool withPaths, bool onlyOutputsToInstall)
{
if (outputs.empty()) {
/* Get the ‘outputs’ list. */
Bindings::iterator i;
if (attrs && (i = attrs->find(state->sOutputs)) != attrs->end()) {
- state->forceList(*i->value, *i->pos);
+ state->forceList(*i->value, i->pos);
/* For each output... */
for (auto elem : i->value->listItems()) {
- /* Evaluate the corresponding set. */
- std::string name(state->forceStringNoCtx(*elem, *i->pos));
- Bindings::iterator out = attrs->find(state->symbols.create(name));
- if (out == attrs->end()) continue; // FIXME: throw error?
- state->forceAttrs(*out->value, *i->pos);
-
- /* And evaluate its ‘outPath’ attribute. */
- Bindings::iterator outPath = out->value->attrs->find(state->sOutPath);
- if (outPath == out->value->attrs->end()) continue; // FIXME: throw error?
- PathSet context;
- outputs[name] = state->coerceToPath(*outPath->pos, *outPath->value, context);
+ std::string output(state->forceStringNoCtx(*elem, i->pos));
+
+ if (withPaths) {
+ /* Evaluate the corresponding set. */
+ Bindings::iterator out = attrs->find(state->symbols.create(output));
+ if (out == attrs->end()) continue; // FIXME: throw error?
+ state->forceAttrs(*out->value, i->pos);
+
+ /* And evaluate its ‘outPath’ attribute. */
+ Bindings::iterator outPath = out->value->attrs->find(state->sOutPath);
+ if (outPath == out->value->attrs->end()) continue; // FIXME: throw error?
+ PathSet context;
+ outputs.emplace(output, state->coerceToStorePath(outPath->pos, *outPath->value, context));
+ } else
+ outputs.emplace(output, std::nullopt);
}
} else
- outputs["out"] = queryOutPath();
+ outputs.emplace("out", withPaths ? std::optional{queryOutPath()} : std::nullopt);
}
+
if (!onlyOutputsToInstall || !attrs)
return outputs;
- /* Check for `meta.outputsToInstall` and return `outputs` reduced to that. */
- const Value * outTI = queryMeta("outputsToInstall");
- if (!outTI) return outputs;
- const auto errMsg = Error("this derivation has bad 'meta.outputsToInstall'");
- /* ^ this shows during `nix-env -i` right under the bad derivation */
- if (!outTI->isList()) throw errMsg;
- Outputs result;
- for (auto elem : outTI->listItems()) {
- if (elem->type() != nString) throw errMsg;
- auto out = outputs.find(elem->string.s);
- if (out == outputs.end()) throw errMsg;
+ Bindings::iterator i;
+ if (attrs && (i = attrs->find(state->sOutputSpecified)) != attrs->end() && state->forceBool(*i->value, i->pos)) {
+ Outputs result;
+ auto out = outputs.find(queryOutputName());
+ if (out == outputs.end())
+ throw Error("derivation does not have output '%s'", queryOutputName());
result.insert(*out);
+ return result;
+ }
+
+ else {
+ /* Check for `meta.outputsToInstall` and return `outputs` reduced to that. */
+ const Value * outTI = queryMeta("outputsToInstall");
+ if (!outTI) return outputs;
+ const auto errMsg = Error("this derivation has bad 'meta.outputsToInstall'");
+ /* ^ this shows during `nix-env -i` right under the bad derivation */
+ if (!outTI->isList()) throw errMsg;
+ Outputs result;
+ for (auto elem : outTI->listItems()) {
+ if (elem->type() != nString) throw errMsg;
+ auto out = outputs.find(elem->string.s);
+ if (out == outputs.end()) throw errMsg;
+ result.insert(*out);
+ }
+ return result;
}
- return result;
}
@@ -154,7 +181,7 @@ Bindings * DrvInfo::getMeta()
if (!attrs) return 0;
Bindings::iterator a = attrs->find(state->sMeta);
if (a == attrs->end()) return 0;
- state->forceAttrs(*a->value, *a->pos);
+ state->forceAttrs(*a->value, a->pos);
meta = a->value->attrs;
return meta;
}
@@ -165,7 +192,7 @@ StringSet DrvInfo::queryMetaNames()
StringSet res;
if (!getMeta()) return res;
for (auto & i : *meta)
- res.insert(i.name);
+ res.emplace(state->symbols[i.name]);
return res;
}
@@ -255,7 +282,7 @@ void DrvInfo::setMeta(const std::string & name, Value * v)
{
getMeta();
auto attrs = state->buildBindings(1 + (meta ? meta->size() : 0));
- Symbol sym = state->symbols.create(name);
+ auto sym = state->symbols.create(name);
if (meta)
for (auto i : *meta)
if (i.name != sym)
@@ -342,11 +369,11 @@ static void getDerivations(EvalState & state, Value & vIn,
there are names clashes between derivations, the derivation
bound to the attribute with the "lower" name should take
precedence). */
- for (auto & i : v.attrs->lexicographicOrder()) {
- debug("evaluating attribute '%1%'", i->name);
- if (!std::regex_match(std::string(i->name), attrRegex))
+ for (auto & i : v.attrs->lexicographicOrder(state.symbols)) {
+ debug("evaluating attribute '%1%'", state.symbols[i->name]);
+ if (!std::regex_match(std::string(state.symbols[i->name]), attrRegex))
continue;
- std::string pathPrefix2 = addToPath(pathPrefix, i->name);
+ std::string pathPrefix2 = addToPath(pathPrefix, state.symbols[i->name]);
if (combineChannels)
getDerivations(state, *i->value, pathPrefix2, autoArgs, drvs, done, ignoreAssertionFailures);
else if (getDerivation(state, *i->value, pathPrefix2, drvs, done, ignoreAssertionFailures)) {
@@ -355,7 +382,7 @@ static void getDerivations(EvalState & state, Value & vIn,
`recurseForDerivations = true' attribute. */
if (i->value->type() == nAttrs) {
Bindings::iterator j = i->value->attrs->find(state.sRecurseForDerivations);
- if (j != i->value->attrs->end() && state.forceBool(*j->value, *j->pos))
+ if (j != i->value->attrs->end() && state.forceBool(*j->value, j->pos))
getDerivations(state, *i->value, pathPrefix2, autoArgs, drvs, done, ignoreAssertionFailures);
}
}
diff --git a/src/libexpr/get-drvs.hh b/src/libexpr/get-drvs.hh
index d13847785..bbd2d3c47 100644
--- a/src/libexpr/get-drvs.hh
+++ b/src/libexpr/get-drvs.hh
@@ -1,6 +1,7 @@
#pragma once
#include "eval.hh"
+#include "path.hh"
#include <string>
#include <map>
@@ -12,15 +13,15 @@ namespace nix {
struct DrvInfo
{
public:
- typedef std::map<std::string, Path> Outputs;
+ typedef std::map<std::string, std::optional<StorePath>> Outputs;
private:
EvalState * state;
mutable std::string name;
mutable std::string system;
- mutable std::string drvPath;
- mutable std::optional<std::string> outPath;
+ mutable std::optional<std::optional<StorePath>> drvPath;
+ mutable std::optional<StorePath> outPath;
mutable std::string outputName;
Outputs outputs;
@@ -41,11 +42,13 @@ public:
std::string queryName() const;
std::string querySystem() const;
- std::string queryDrvPath() const;
- std::string queryOutPath() const;
+ std::optional<StorePath> queryDrvPath() const;
+ StorePath requireDrvPath() const;
+ StorePath queryOutPath() const;
std::string queryOutputName() const;
- /** Return the list of outputs. The "outputs to install" are determined by `meta.outputsToInstall`. */
- Outputs queryOutputs(bool onlyOutputsToInstall = false);
+ /** Return the unordered map of output names to (optional) output paths.
+ * The "outputs to install" are determined by `meta.outputsToInstall`. */
+ Outputs queryOutputs(bool withPaths = true, bool onlyOutputsToInstall = false);
StringSet queryMetaNames();
Value * queryMeta(const std::string & name);
@@ -61,8 +64,8 @@ public:
*/
void setName(const std::string & s) { name = s; }
- void setDrvPath(const std::string & s) { drvPath = s; }
- void setOutPath(const std::string & s) { outPath = s; }
+ void setDrvPath(StorePath path) { drvPath = {{std::move(path)}}; }
+ void setOutPath(StorePath path) { outPath = {{std::move(path)}}; }
void setFailed() { failed = true; };
bool hasFailed() { return failed; };
@@ -70,7 +73,7 @@ public:
#if HAVE_BOEHMGC
-typedef std::list<DrvInfo, traceable_allocator<DrvInfo> > DrvInfos;
+typedef std::list<DrvInfo, traceable_allocator<DrvInfo>> DrvInfos;
#else
typedef std::list<DrvInfo> DrvInfos;
#endif
diff --git a/src/libexpr/lexer.l b/src/libexpr/lexer.l
index e276b0467..462b3b602 100644
--- a/src/libexpr/lexer.l
+++ b/src/libexpr/lexer.l
@@ -28,6 +28,13 @@ using namespace nix;
namespace nix {
+static inline PosIdx makeCurPos(const YYLTYPE & loc, ParseData * data)
+{
+ return data->state.positions.add(data->origin, loc.first_line, loc.first_column);
+}
+
+#define CUR_POS makeCurPos(*yylloc, data)
+
// backup to recover from yyless(0)
YYLTYPE prev_yylloc;
@@ -37,7 +44,6 @@ static void initLoc(YYLTYPE * loc)
loc->first_column = loc->last_column = 1;
}
-
static void adjustLoc(YYLTYPE * loc, const char * s, size_t len)
{
prev_yylloc = *loc;
@@ -147,14 +153,20 @@ or { return OR_KW; }
try {
yylval->n = boost::lexical_cast<int64_t>(yytext);
} catch (const boost::bad_lexical_cast &) {
- throw ParseError("invalid integer '%1%'", yytext);
+ throw ParseError({
+ .msg = hintfmt("invalid integer '%1%'", yytext),
+ .errPos = data->state.positions[CUR_POS],
+ });
}
return INT;
}
{FLOAT} { errno = 0;
yylval->nf = strtod(yytext, 0);
if (errno != 0)
- throw ParseError("invalid float '%1%'", yytext);
+ throw ParseError({
+ .msg = hintfmt("invalid float '%1%'", yytext),
+ .errPos = data->state.positions[CUR_POS],
+ });
return FLOAT;
}
@@ -186,7 +198,7 @@ or { return OR_KW; }
(...|\$[^\{\"\\]|\\.|\$\\.)+ would have triggered.
This is technically invalid, but we leave the problem to the
parser who fails with exact location. */
- return STR;
+ return EOF;
}
\'\'(\ *\n)? { PUSH_STATE(IND_STRING); return IND_STRING_OPEN; }
@@ -280,7 +292,10 @@ or { return OR_KW; }
<INPATH_SLASH>{ANY} |
<INPATH_SLASH><<EOF>> {
- throw ParseError("path has a trailing slash");
+ throw ParseError({
+ .msg = hintfmt("path has a trailing slash"),
+ .errPos = data->state.positions[CUR_POS],
+ });
}
{SPATH} { yylval->path = {yytext, (size_t) yyleng}; return SPATH; }
diff --git a/src/libexpr/nixexpr.cc b/src/libexpr/nixexpr.cc
index a2def65a6..7c623a07d 100644
--- a/src/libexpr/nixexpr.cc
+++ b/src/libexpr/nixexpr.cc
@@ -1,21 +1,15 @@
#include "nixexpr.hh"
#include "derivations.hh"
+#include "eval.hh"
+#include "symbol-table.hh"
#include "util.hh"
#include <cstdlib>
-
namespace nix {
-
/* Displaying abstract syntax trees. */
-std::ostream & operator << (std::ostream & str, const Expr & e)
-{
- e.show(str);
- return str;
-}
-
static void showString(std::ostream & str, std::string_view s)
{
str << '"';
@@ -28,8 +22,10 @@ static void showString(std::ostream & str, std::string_view s)
str << '"';
}
-static void showId(std::ostream & str, std::string_view s)
+std::ostream & operator <<(std::ostream & str, const SymbolStr & symbol)
{
+ std::string_view s = symbol;
+
if (s.empty())
str << "\"\"";
else if (s == "if") // FIXME: handle other keywords
@@ -38,7 +34,7 @@ static void showId(std::ostream & str, std::string_view s)
char c = s[0];
if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_')) {
showString(str, s);
- return;
+ return str;
}
for (auto c : s)
if (!((c >= 'a' && c <= 'z') ||
@@ -46,89 +42,104 @@ static void showId(std::ostream & str, std::string_view s)
(c >= '0' && c <= '9') ||
c == '_' || c == '\'' || c == '-')) {
showString(str, s);
- return;
+ return str;
}
str << s;
}
-}
-
-std::ostream & operator << (std::ostream & str, const Symbol & sym)
-{
- showId(str, *sym.s);
return str;
}
-void Expr::show(std::ostream & str) const
+void Expr::show(const SymbolTable & symbols, std::ostream & str) const
{
abort();
}
-void ExprInt::show(std::ostream & str) const
+void ExprInt::show(const SymbolTable & symbols, std::ostream & str) const
{
str << n;
}
-void ExprFloat::show(std::ostream & str) const
+void ExprFloat::show(const SymbolTable & symbols, std::ostream & str) const
{
str << nf;
}
-void ExprString::show(std::ostream & str) const
+void ExprString::show(const SymbolTable & symbols, std::ostream & str) const
{
showString(str, s);
}
-void ExprPath::show(std::ostream & str) const
+void ExprPath::show(const SymbolTable & symbols, std::ostream & str) const
{
str << s;
}
-void ExprVar::show(std::ostream & str) const
+void ExprVar::show(const SymbolTable & symbols, std::ostream & str) const
{
- str << name;
+ str << symbols[name];
}
-void ExprSelect::show(std::ostream & str) const
+void ExprSelect::show(const SymbolTable & symbols, std::ostream & str) const
{
- str << "(" << *e << ")." << showAttrPath(attrPath);
- if (def) str << " or (" << *def << ")";
+ str << "(";
+ e->show(symbols, str);
+ str << ")." << showAttrPath(symbols, attrPath);
+ if (def) {
+ str << " or (";
+ def->show(symbols, str);
+ str << ")";
+ }
}
-void ExprOpHasAttr::show(std::ostream & str) const
+void ExprOpHasAttr::show(const SymbolTable & symbols, std::ostream & str) const
{
- str << "((" << *e << ") ? " << showAttrPath(attrPath) << ")";
+ str << "((";
+ e->show(symbols, str);
+ str << ") ? " << showAttrPath(symbols, attrPath) << ")";
}
-void ExprAttrs::show(std::ostream & str) const
+void ExprAttrs::show(const SymbolTable & symbols, std::ostream & str) const
{
if (recursive) str << "rec ";
str << "{ ";
typedef const decltype(attrs)::value_type * Attr;
std::vector<Attr> sorted;
for (auto & i : attrs) sorted.push_back(&i);
- std::sort(sorted.begin(), sorted.end(), [](Attr a, Attr b) {
- return (const std::string &) a->first < (const std::string &) b->first;
- });
+ std::sort(sorted.begin(), sorted.end(), [&](Attr a, Attr b) {
+ std::string_view sa = symbols[a->first], sb = symbols[b->first];
+ return sa < sb;
+ });
for (auto & i : sorted) {
if (i->second.inherited)
- str << "inherit " << i->first << " " << "; ";
- else
- str << i->first << " = " << *i->second.e << "; ";
+ str << "inherit " << symbols[i->first] << " " << "; ";
+ else {
+ str << symbols[i->first] << " = ";
+ i->second.e->show(symbols, str);
+ str << "; ";
+ }
+ }
+ for (auto & i : dynamicAttrs) {
+ str << "\"${";
+ i.nameExpr->show(symbols, str);
+ str << "}\" = ";
+ i.valueExpr->show(symbols, str);
+ str << "; ";
}
- for (auto & i : dynamicAttrs)
- str << "\"${" << *i.nameExpr << "}\" = " << *i.valueExpr << "; ";
str << "}";
}
-void ExprList::show(std::ostream & str) const
+void ExprList::show(const SymbolTable & symbols, std::ostream & str) const
{
str << "[ ";
- for (auto & i : elems)
- str << "(" << *i << ") ";
+ for (auto & i : elems) {
+ str << "(";
+ i->show(symbols, str);
+ str << ") ";
+ }
str << "]";
}
-void ExprLambda::show(std::ostream & str) const
+void ExprLambda::show(const SymbolTable & symbols, std::ostream & str) const
{
str << "(";
if (hasFormals()) {
@@ -136,74 +147,100 @@ void ExprLambda::show(std::ostream & str) const
bool first = true;
for (auto & i : formals->formals) {
if (first) first = false; else str << ", ";
- str << i.name;
- if (i.def) str << " ? " << *i.def;
+ str << symbols[i.name];
+ if (i.def) {
+ str << " ? ";
+ i.def->show(symbols, str);
+ }
}
if (formals->ellipsis) {
if (!first) str << ", ";
str << "...";
}
str << " }";
- if (!arg.empty()) str << " @ ";
+ if (arg) str << " @ ";
}
- if (!arg.empty()) str << arg;
- str << ": " << *body << ")";
+ if (arg) str << symbols[arg];
+ str << ": ";
+ body->show(symbols, str);
+ str << ")";
}
-void ExprCall::show(std::ostream & str) const
+void ExprCall::show(const SymbolTable & symbols, std::ostream & str) const
{
- str << '(' << *fun;
+ str << '(';
+ fun->show(symbols, str);
for (auto e : args) {
str << ' ';
- str << *e;
+ e->show(symbols, str);
}
str << ')';
}
-void ExprLet::show(std::ostream & str) const
+void ExprLet::show(const SymbolTable & symbols, std::ostream & str) const
{
str << "(let ";
for (auto & i : attrs->attrs)
if (i.second.inherited) {
- str << "inherit " << i.first << "; ";
+ str << "inherit " << symbols[i.first] << "; ";
}
- else
- str << i.first << " = " << *i.second.e << "; ";
- str << "in " << *body << ")";
+ else {
+ str << symbols[i.first] << " = ";
+ i.second.e->show(symbols, str);
+ str << "; ";
+ }
+ str << "in ";
+ body->show(symbols, str);
+ str << ")";
}
-void ExprWith::show(std::ostream & str) const
+void ExprWith::show(const SymbolTable & symbols, std::ostream & str) const
{
- str << "(with " << *attrs << "; " << *body << ")";
+ str << "(with ";
+ attrs->show(symbols, str);
+ str << "; ";
+ body->show(symbols, str);
+ str << ")";
}
-void ExprIf::show(std::ostream & str) const
+void ExprIf::show(const SymbolTable & symbols, std::ostream & str) const
{
- str << "(if " << *cond << " then " << *then << " else " << *else_ << ")";
+ str << "(if ";
+ cond->show(symbols, str);
+ str << " then ";
+ then->show(symbols, str);
+ str << " else ";
+ else_->show(symbols, str);
+ str << ")";
}
-void ExprAssert::show(std::ostream & str) const
+void ExprAssert::show(const SymbolTable & symbols, std::ostream & str) const
{
- str << "assert " << *cond << "; " << *body;
+ str << "assert ";
+ cond->show(symbols, str);
+ str << "; ";
+ body->show(symbols, str);
}
-void ExprOpNot::show(std::ostream & str) const
+void ExprOpNot::show(const SymbolTable & symbols, std::ostream & str) const
{
- str << "(! " << *e << ")";
+ str << "(! ";
+ e->show(symbols, str);
+ str << ")";
}
-void ExprConcatStrings::show(std::ostream & str) const
+void ExprConcatStrings::show(const SymbolTable & symbols, std::ostream & str) const
{
bool first = true;
str << "(";
for (auto & i : *es) {
if (first) first = false; else str << " + ";
- str << *i.second;
+ i.second->show(symbols, str);
}
str << ")";
}
-void ExprPos::show(std::ostream & str) const
+void ExprPos::show(const SymbolTable & symbols, std::ostream & str) const
{
str << "__curPos";
}
@@ -234,55 +271,67 @@ std::ostream & operator << (std::ostream & str, const Pos & pos)
}
-std::string showAttrPath(const AttrPath & attrPath)
+std::string showAttrPath(const SymbolTable & symbols, const AttrPath & attrPath)
{
std::ostringstream out;
bool first = true;
for (auto & i : attrPath) {
if (!first) out << '.'; else first = false;
- if (i.symbol.set())
- out << i.symbol;
- else
- out << "\"${" << *i.expr << "}\"";
+ if (i.symbol)
+ out << symbols[i.symbol];
+ else {
+ out << "\"${";
+ i.expr->show(symbols, out);
+ out << "}\"";
+ }
}
return out.str();
}
-Pos noPos;
-
/* Computing levels/displacements for variables. */
-void Expr::bindVars(const StaticEnv & env)
+void Expr::bindVars(EvalState & es, const std::shared_ptr<const StaticEnv> & env)
{
abort();
}
-void ExprInt::bindVars(const StaticEnv & env)
+void ExprInt::bindVars(EvalState & es, const std::shared_ptr<const StaticEnv> & env)
{
+ if (es.debugRepl)
+ es.exprEnvs.insert(std::make_pair(this, env));
}
-void ExprFloat::bindVars(const StaticEnv & env)
+void ExprFloat::bindVars(EvalState & es, const std::shared_ptr<const StaticEnv> & env)
{
+ if (es.debugRepl)
+ es.exprEnvs.insert(std::make_pair(this, env));
}
-void ExprString::bindVars(const StaticEnv & env)
+void ExprString::bindVars(EvalState & es, const std::shared_ptr<const StaticEnv> & env)
{
+ if (es.debugRepl)
+ es.exprEnvs.insert(std::make_pair(this, env));
}
-void ExprPath::bindVars(const StaticEnv & env)
+void ExprPath::bindVars(EvalState & es, const std::shared_ptr<const StaticEnv> & env)
{
+ if (es.debugRepl)
+ es.exprEnvs.insert(std::make_pair(this, env));
}
-void ExprVar::bindVars(const StaticEnv & env)
+void ExprVar::bindVars(EvalState & es, const std::shared_ptr<const StaticEnv> & env)
{
+ if (es.debugRepl)
+ es.exprEnvs.insert(std::make_pair(this, env));
+
/* Check whether the variable appears in the environment. If so,
set its level and displacement. */
const StaticEnv * curEnv;
Level level;
int withLevel = -1;
- for (curEnv = &env, level = 0; curEnv; curEnv = curEnv->up, level++) {
+ for (curEnv = env.get(), level = 0; curEnv; curEnv = curEnv->up, level++) {
if (curEnv->isWith) {
if (withLevel == -1) withLevel = level;
} else {
@@ -301,176 +350,222 @@ void ExprVar::bindVars(const StaticEnv & env)
"undefined variable" error now. */
if (withLevel == -1)
throw UndefinedVarError({
- .msg = hintfmt("undefined variable '%1%'", name),
- .errPos = pos
+ .msg = hintfmt("undefined variable '%1%'", es.symbols[name]),
+ .errPos = es.positions[pos]
});
fromWith = true;
this->level = withLevel;
}
-void ExprSelect::bindVars(const StaticEnv & env)
+void ExprSelect::bindVars(EvalState & es, const std::shared_ptr<const StaticEnv> & env)
{
- e->bindVars(env);
- if (def) def->bindVars(env);
+ if (es.debugRepl)
+ es.exprEnvs.insert(std::make_pair(this, env));
+
+ e->bindVars(es, env);
+ if (def) def->bindVars(es, env);
for (auto & i : attrPath)
- if (!i.symbol.set())
- i.expr->bindVars(env);
+ if (!i.symbol)
+ i.expr->bindVars(es, env);
}
-void ExprOpHasAttr::bindVars(const StaticEnv & env)
+void ExprOpHasAttr::bindVars(EvalState & es, const std::shared_ptr<const StaticEnv> & env)
{
- e->bindVars(env);
+ if (es.debugRepl)
+ es.exprEnvs.insert(std::make_pair(this, env));
+
+ e->bindVars(es, env);
for (auto & i : attrPath)
- if (!i.symbol.set())
- i.expr->bindVars(env);
+ if (!i.symbol)
+ i.expr->bindVars(es, env);
}
-void ExprAttrs::bindVars(const StaticEnv & env)
+void ExprAttrs::bindVars(EvalState & es, const std::shared_ptr<const StaticEnv> & env)
{
- const StaticEnv * dynamicEnv = &env;
- StaticEnv newEnv(false, &env, recursive ? attrs.size() : 0);
+ if (es.debugRepl)
+ es.exprEnvs.insert(std::make_pair(this, env));
if (recursive) {
- dynamicEnv = &newEnv;
+ auto newEnv = std::make_shared<StaticEnv>(false, env.get(), recursive ? attrs.size() : 0);
Displacement displ = 0;
for (auto & i : attrs)
- newEnv.vars.emplace_back(i.first, i.second.displ = displ++);
+ newEnv->vars.emplace_back(i.first, i.second.displ = displ++);
// No need to sort newEnv since attrs is in sorted order.
for (auto & i : attrs)
- i.second.e->bindVars(i.second.inherited ? env : newEnv);
- }
+ i.second.e->bindVars(es, i.second.inherited ? env : newEnv);
- else
+ for (auto & i : dynamicAttrs) {
+ i.nameExpr->bindVars(es, newEnv);
+ i.valueExpr->bindVars(es, newEnv);
+ }
+ }
+ else {
for (auto & i : attrs)
- i.second.e->bindVars(env);
+ i.second.e->bindVars(es, env);
- for (auto & i : dynamicAttrs) {
- i.nameExpr->bindVars(*dynamicEnv);
- i.valueExpr->bindVars(*dynamicEnv);
+ for (auto & i : dynamicAttrs) {
+ i.nameExpr->bindVars(es, env);
+ i.valueExpr->bindVars(es, env);
+ }
}
}
-void ExprList::bindVars(const StaticEnv & env)
+void ExprList::bindVars(EvalState & es, const std::shared_ptr<const StaticEnv> & env)
{
+ if (es.debugRepl)
+ es.exprEnvs.insert(std::make_pair(this, env));
+
for (auto & i : elems)
- i->bindVars(env);
+ i->bindVars(es, env);
}
-void ExprLambda::bindVars(const StaticEnv & env)
+void ExprLambda::bindVars(EvalState & es, const std::shared_ptr<const StaticEnv> & env)
{
- StaticEnv newEnv(
- false, &env,
+ if (es.debugRepl)
+ es.exprEnvs.insert(std::make_pair(this, env));
+
+ auto newEnv = std::make_shared<StaticEnv>(
+ false, env.get(),
(hasFormals() ? formals->formals.size() : 0) +
- (arg.empty() ? 0 : 1));
+ (!arg ? 0 : 1));
Displacement displ = 0;
- if (!arg.empty()) newEnv.vars.emplace_back(arg, displ++);
+ if (arg) newEnv->vars.emplace_back(arg, displ++);
if (hasFormals()) {
for (auto & i : formals->formals)
- newEnv.vars.emplace_back(i.name, displ++);
+ newEnv->vars.emplace_back(i.name, displ++);
- newEnv.sort();
+ newEnv->sort();
for (auto & i : formals->formals)
- if (i.def) i.def->bindVars(newEnv);
+ if (i.def) i.def->bindVars(es, newEnv);
}
- body->bindVars(newEnv);
+ body->bindVars(es, newEnv);
}
-void ExprCall::bindVars(const StaticEnv & env)
+void ExprCall::bindVars(EvalState & es, const std::shared_ptr<const StaticEnv> & env)
{
- fun->bindVars(env);
+ if (es.debugRepl)
+ es.exprEnvs.insert(std::make_pair(this, env));
+
+ fun->bindVars(es, env);
for (auto e : args)
- e->bindVars(env);
+ e->bindVars(es, env);
}
-void ExprLet::bindVars(const StaticEnv & env)
+void ExprLet::bindVars(EvalState & es, const std::shared_ptr<const StaticEnv> & env)
{
- StaticEnv newEnv(false, &env, attrs->attrs.size());
+ if (es.debugRepl)
+ es.exprEnvs.insert(std::make_pair(this, env));
+
+ auto newEnv = std::make_shared<StaticEnv>(false, env.get(), attrs->attrs.size());
Displacement displ = 0;
for (auto & i : attrs->attrs)
- newEnv.vars.emplace_back(i.first, i.second.displ = displ++);
+ newEnv->vars.emplace_back(i.first, i.second.displ = displ++);
// No need to sort newEnv since attrs->attrs is in sorted order.
for (auto & i : attrs->attrs)
- i.second.e->bindVars(i.second.inherited ? env : newEnv);
+ i.second.e->bindVars(es, i.second.inherited ? env : newEnv);
- body->bindVars(newEnv);
+ body->bindVars(es, newEnv);
}
-void ExprWith::bindVars(const StaticEnv & env)
+void ExprWith::bindVars(EvalState & es, const std::shared_ptr<const StaticEnv> & env)
{
+ if (es.debugRepl)
+ es.exprEnvs.insert(std::make_pair(this, env));
+
/* Does this `with' have an enclosing `with'? If so, record its
level so that `lookupVar' can look up variables in the previous
`with' if this one doesn't contain the desired attribute. */
const StaticEnv * curEnv;
Level level;
prevWith = 0;
- for (curEnv = &env, level = 1; curEnv; curEnv = curEnv->up, level++)
+ for (curEnv = env.get(), level = 1; curEnv; curEnv = curEnv->up, level++)
if (curEnv->isWith) {
prevWith = level;
break;
}
- attrs->bindVars(env);
- StaticEnv newEnv(true, &env);
- body->bindVars(newEnv);
+ if (es.debugRepl)
+ es.exprEnvs.insert(std::make_pair(this, env));
+
+ attrs->bindVars(es, env);
+ auto newEnv = std::make_shared<StaticEnv>(true, env.get());
+ body->bindVars(es, newEnv);
}
-void ExprIf::bindVars(const StaticEnv & env)
+void ExprIf::bindVars(EvalState & es, const std::shared_ptr<const StaticEnv> & env)
{
- cond->bindVars(env);
- then->bindVars(env);
- else_->bindVars(env);
+ if (es.debugRepl)
+ es.exprEnvs.insert(std::make_pair(this, env));
+
+ cond->bindVars(es, env);
+ then->bindVars(es, env);
+ else_->bindVars(es, env);
}
-void ExprAssert::bindVars(const StaticEnv & env)
+void ExprAssert::bindVars(EvalState & es, const std::shared_ptr<const StaticEnv> & env)
{
- cond->bindVars(env);
- body->bindVars(env);
+ if (es.debugRepl)
+ es.exprEnvs.insert(std::make_pair(this, env));
+
+ cond->bindVars(es, env);
+ body->bindVars(es, env);
}
-void ExprOpNot::bindVars(const StaticEnv & env)
+void ExprOpNot::bindVars(EvalState & es, const std::shared_ptr<const StaticEnv> & env)
{
- e->bindVars(env);
+ if (es.debugRepl)
+ es.exprEnvs.insert(std::make_pair(this, env));
+
+ e->bindVars(es, env);
}
-void ExprConcatStrings::bindVars(const StaticEnv & env)
+void ExprConcatStrings::bindVars(EvalState & es, const std::shared_ptr<const StaticEnv> & env)
{
- for (auto & i : *es)
- i.second->bindVars(env);
+ if (es.debugRepl)
+ es.exprEnvs.insert(std::make_pair(this, env));
+
+ for (auto & i : *this->es)
+ i.second->bindVars(es, env);
}
-void ExprPos::bindVars(const StaticEnv & env)
+void ExprPos::bindVars(EvalState & es, const std::shared_ptr<const StaticEnv> & env)
{
+ if (es.debugRepl)
+ es.exprEnvs.insert(std::make_pair(this, env));
}
/* Storing function names. */
-void Expr::setName(Symbol & name)
+void Expr::setName(Symbol name)
{
}
-void ExprLambda::setName(Symbol & name)
+void ExprLambda::setName(Symbol name)
{
this->name = name;
body->setName(name);
}
-std::string ExprLambda::showNamePos() const
+std::string ExprLambda::showNamePos(const EvalState & state) const
{
- return fmt("%1% at %2%", name.set() ? "'" + (std::string) name + "'" : "anonymous function", pos);
+ std::string id(name
+ ? concatStrings("'", state.symbols[name], "'")
+ : "anonymous function");
+ return fmt("%1% at %2%", id, state.positions[pos]);
}
@@ -480,8 +575,7 @@ std::string ExprLambda::showNamePos() const
size_t SymbolTable::totalSize() const
{
size_t n = 0;
- for (auto & i : store)
- n += i.size();
+ dump([&] (const std::string & s) { n += s.size(); });
return n;
}
diff --git a/src/libexpr/nixexpr.hh b/src/libexpr/nixexpr.hh
index 12b54b8eb..5eb022770 100644
--- a/src/libexpr/nixexpr.hh
+++ b/src/libexpr/nixexpr.hh
@@ -1,8 +1,12 @@
#pragma once
+#include <map>
+#include <vector>
+
#include "value.hh"
#include "symbol-table.hh"
#include "error.hh"
+#include "chunked-vector.hh"
namespace nix {
@@ -18,38 +22,96 @@ MakeError(UndefinedVarError, Error);
MakeError(MissingArgumentError, EvalError);
MakeError(RestrictedPathError, Error);
-
/* Position objects. */
struct Pos
{
+ std::string file;
FileOrigin origin;
- Symbol file;
- unsigned int line, column;
+ uint32_t line;
+ uint32_t column;
+
+ explicit operator bool() const { return line > 0; }
+};
+
+class PosIdx {
+ friend class PosTable;
+
+private:
+ uint32_t id;
+
+ explicit PosIdx(uint32_t id): id(id) {}
- Pos() : origin(foString), line(0), column(0) { }
- Pos(FileOrigin origin, const Symbol & file, unsigned int line, unsigned int column)
- : origin(origin), file(file), line(line), column(column) { }
+public:
+ PosIdx() : id(0) {}
- operator bool() const
+ explicit operator bool() const { return id > 0; }
+
+ bool operator<(const PosIdx other) const { return id < other.id; }
+};
+
+class PosTable
+{
+public:
+ class Origin {
+ friend PosTable;
+ private:
+ // must always be invalid by default, add() replaces this with the actual value.
+ // subsequent add() calls use this index as a token to quickly check whether the
+ // current origins.back() can be reused or not.
+ mutable uint32_t idx = std::numeric_limits<uint32_t>::max();
+
+ explicit Origin(uint32_t idx): idx(idx), file{}, origin{} {}
+
+ public:
+ const std::string file;
+ const FileOrigin origin;
+
+ Origin(std::string file, FileOrigin origin): file(std::move(file)), origin(origin) {}
+ };
+
+ struct Offset {
+ uint32_t line, column;
+ };
+
+private:
+ std::vector<Origin> origins;
+ ChunkedVector<Offset, 8192> offsets;
+
+public:
+ PosTable(): offsets(1024)
{
- return line != 0;
+ origins.reserve(1024);
}
- bool operator < (const Pos & p2) const
+ PosIdx add(const Origin & origin, uint32_t line, uint32_t column)
{
- if (!line) return p2.line;
- if (!p2.line) return false;
- int d = ((const std::string &) file).compare((const std::string &) p2.file);
- if (d < 0) return true;
- if (d > 0) return false;
- if (line < p2.line) return true;
- if (line > p2.line) return false;
- return column < p2.column;
+ const auto idx = offsets.add({line, column}).second;
+ if (origins.empty() || origins.back().idx != origin.idx) {
+ origin.idx = idx;
+ origins.push_back(origin);
+ }
+ return PosIdx(idx + 1);
+ }
+
+ Pos operator[](PosIdx p) const
+ {
+ if (p.id == 0 || p.id > offsets.size())
+ return {};
+ const auto idx = p.id - 1;
+ /* we want the last key <= idx, so we'll take prev(first key > idx).
+ this is guaranteed to never rewind origin.begin because the first
+ key is always 0. */
+ const auto pastOrigin = std::upper_bound(
+ origins.begin(), origins.end(), Origin(idx),
+ [] (const auto & a, const auto & b) { return a.idx < b.idx; });
+ const auto origin = *std::prev(pastOrigin);
+ const auto offset = offsets[idx];
+ return {origin.file, origin.origin, offset.line, offset.column};
}
};
-extern Pos noPos;
+inline PosIdx noPos = {};
std::ostream & operator << (std::ostream & str, const Pos & pos);
@@ -65,13 +127,13 @@ struct AttrName
{
Symbol symbol;
Expr * expr;
- AttrName(const Symbol & s) : symbol(s) {};
+ AttrName(Symbol s) : symbol(s) {};
AttrName(Expr * e) : expr(e) {};
};
typedef std::vector<AttrName> AttrPath;
-std::string showAttrPath(const AttrPath & attrPath);
+std::string showAttrPath(const SymbolTable & symbols, const AttrPath & attrPath);
/* Abstract syntax of Nix expressions. */
@@ -79,27 +141,26 @@ std::string showAttrPath(const AttrPath & attrPath);
struct Expr
{
virtual ~Expr() { };
- virtual void show(std::ostream & str) const;
- virtual void bindVars(const StaticEnv & env);
+ virtual void show(const SymbolTable & symbols, std::ostream & str) const;
+ virtual void bindVars(EvalState & es, const std::shared_ptr<const StaticEnv> & env);
virtual void eval(EvalState & state, Env & env, Value & v);
virtual Value * maybeThunk(EvalState & state, Env & env);
- virtual void setName(Symbol & name);
+ virtual void setName(Symbol name);
+ virtual PosIdx getPos() const { return noPos; }
};
-std::ostream & operator << (std::ostream & str, const Expr & e);
-
#define COMMON_METHODS \
- void show(std::ostream & str) const; \
- void eval(EvalState & state, Env & env, Value & v); \
- void bindVars(const StaticEnv & env);
+ void show(const SymbolTable & symbols, std::ostream & str) const override; \
+ void eval(EvalState & state, Env & env, Value & v) override; \
+ void bindVars(EvalState & es, const std::shared_ptr<const StaticEnv> & env) override;
struct ExprInt : Expr
{
NixInt n;
Value v;
ExprInt(NixInt n) : n(n) { v.mkInt(n); };
+ Value * maybeThunk(EvalState & state, Env & env) override;
COMMON_METHODS
- Value * maybeThunk(EvalState & state, Env & env);
};
struct ExprFloat : Expr
@@ -107,8 +168,8 @@ struct ExprFloat : Expr
NixFloat nf;
Value v;
ExprFloat(NixFloat nf) : nf(nf) { v.mkFloat(nf); };
+ Value * maybeThunk(EvalState & state, Env & env) override;
COMMON_METHODS
- Value * maybeThunk(EvalState & state, Env & env);
};
struct ExprString : Expr
@@ -116,8 +177,8 @@ struct ExprString : Expr
std::string s;
Value v;
ExprString(std::string s) : s(std::move(s)) { v.mkString(this->s.data()); };
+ Value * maybeThunk(EvalState & state, Env & env) override;
COMMON_METHODS
- Value * maybeThunk(EvalState & state, Env & env);
};
struct ExprPath : Expr
@@ -125,8 +186,8 @@ struct ExprPath : Expr
std::string s;
Value v;
ExprPath(std::string s) : s(std::move(s)) { v.mkPath(this->s.c_str()); };
+ Value * maybeThunk(EvalState & state, Env & env) override;
COMMON_METHODS
- Value * maybeThunk(EvalState & state, Env & env);
};
typedef uint32_t Level;
@@ -134,7 +195,7 @@ typedef uint32_t Displacement;
struct ExprVar : Expr
{
- Pos pos;
+ PosIdx pos;
Symbol name;
/* Whether the variable comes from an environment (e.g. a rec, let
@@ -150,19 +211,21 @@ struct ExprVar : Expr
Level level;
Displacement displ;
- ExprVar(const Symbol & name) : name(name) { };
- ExprVar(const Pos & pos, const Symbol & name) : pos(pos), name(name) { };
+ ExprVar(Symbol name) : name(name) { };
+ ExprVar(const PosIdx & pos, Symbol name) : pos(pos), name(name) { };
+ Value * maybeThunk(EvalState & state, Env & env) override;
+ PosIdx getPos() const override { return pos; }
COMMON_METHODS
- Value * maybeThunk(EvalState & state, Env & env);
};
struct ExprSelect : Expr
{
- Pos pos;
+ PosIdx pos;
Expr * e, * def;
AttrPath attrPath;
- ExprSelect(const Pos & pos, Expr * e, const AttrPath & attrPath, Expr * def) : pos(pos), e(e), def(def), attrPath(attrPath) { };
- ExprSelect(const Pos & pos, Expr * e, const Symbol & name) : pos(pos), e(e), def(0) { attrPath.push_back(AttrName(name)); };
+ ExprSelect(const PosIdx & pos, Expr * e, const AttrPath & attrPath, Expr * def) : pos(pos), e(e), def(def), attrPath(attrPath) { };
+ ExprSelect(const PosIdx & pos, Expr * e, Symbol name) : pos(pos), e(e), def(0) { attrPath.push_back(AttrName(name)); };
+ PosIdx getPos() const override { return pos; }
COMMON_METHODS
};
@@ -171,19 +234,20 @@ struct ExprOpHasAttr : Expr
Expr * e;
AttrPath attrPath;
ExprOpHasAttr(Expr * e, const AttrPath & attrPath) : e(e), attrPath(attrPath) { };
+ PosIdx getPos() const override { return e->getPos(); }
COMMON_METHODS
};
struct ExprAttrs : Expr
{
bool recursive;
- Pos pos;
+ PosIdx pos;
struct AttrDef {
bool inherited;
Expr * e;
- Pos pos;
+ PosIdx pos;
Displacement displ; // displacement
- AttrDef(Expr * e, const Pos & pos, bool inherited=false)
+ AttrDef(Expr * e, const PosIdx & pos, bool inherited=false)
: inherited(inherited), e(e), pos(pos) { };
AttrDef() { };
};
@@ -191,14 +255,15 @@ struct ExprAttrs : Expr
AttrDefs attrs;
struct DynamicAttrDef {
Expr * nameExpr, * valueExpr;
- Pos pos;
- DynamicAttrDef(Expr * nameExpr, Expr * valueExpr, const Pos & pos)
+ PosIdx pos;
+ DynamicAttrDef(Expr * nameExpr, Expr * valueExpr, const PosIdx & pos)
: nameExpr(nameExpr), valueExpr(valueExpr), pos(pos) { };
};
typedef std::vector<DynamicAttrDef> DynamicAttrDefs;
DynamicAttrDefs dynamicAttrs;
- ExprAttrs(const Pos &pos) : recursive(false), pos(pos) { };
- ExprAttrs() : recursive(false), pos(noPos) { };
+ ExprAttrs(const PosIdx &pos) : recursive(false), pos(pos) { };
+ ExprAttrs() : recursive(false) { };
+ PosIdx getPos() const override { return pos; }
COMMON_METHODS
};
@@ -207,14 +272,18 @@ struct ExprList : Expr
std::vector<Expr *> elems;
ExprList() { };
COMMON_METHODS
+
+ PosIdx getPos() const override
+ {
+ return elems.empty() ? noPos : elems.front()->getPos();
+ }
};
struct Formal
{
- Pos pos;
+ PosIdx pos;
Symbol name;
Expr * def;
- Formal(const Pos & pos, const Symbol & name, Expr * def) : pos(pos), name(name), def(def) { };
};
struct Formals
@@ -223,18 +292,20 @@ struct Formals
Formals_ formals;
bool ellipsis;
- bool has(Symbol arg) const {
+ bool has(Symbol arg) const
+ {
auto it = std::lower_bound(formals.begin(), formals.end(), arg,
[] (const Formal & f, const Symbol & sym) { return f.name < sym; });
return it != formals.end() && it->name == arg;
}
- std::vector<Formal> lexicographicOrder() const
+ std::vector<Formal> lexicographicOrder(const SymbolTable & symbols) const
{
std::vector<Formal> result(formals.begin(), formals.end());
std::sort(result.begin(), result.end(),
- [] (const Formal & a, const Formal & b) {
- return std::string_view(a.name) < std::string_view(b.name);
+ [&] (const Formal & a, const Formal & b) {
+ std::string_view sa = symbols[a.name], sb = symbols[b.name];
+ return sa < sb;
});
return result;
}
@@ -242,18 +313,23 @@ struct Formals
struct ExprLambda : Expr
{
- Pos pos;
+ PosIdx pos;
Symbol name;
Symbol arg;
Formals * formals;
Expr * body;
- ExprLambda(const Pos & pos, const Symbol & arg, Formals * formals, Expr * body)
+ ExprLambda(PosIdx pos, Symbol arg, Formals * formals, Expr * body)
: pos(pos), arg(arg), formals(formals), body(body)
{
};
- void setName(Symbol & name);
- std::string showNamePos() const;
+ ExprLambda(PosIdx pos, Formals * formals, Expr * body)
+ : pos(pos), formals(formals), body(body)
+ {
+ }
+ void setName(Symbol name) override;
+ std::string showNamePos(const EvalState & state) const;
inline bool hasFormals() const { return formals != nullptr; }
+ PosIdx getPos() const override { return pos; }
COMMON_METHODS
};
@@ -261,10 +337,11 @@ struct ExprCall : Expr
{
Expr * fun;
std::vector<Expr *> args;
- Pos pos;
- ExprCall(const Pos & pos, Expr * fun, std::vector<Expr *> && args)
+ PosIdx pos;
+ ExprCall(const PosIdx & pos, Expr * fun, std::vector<Expr *> && args)
: fun(fun), args(args), pos(pos)
{ }
+ PosIdx getPos() const override { return pos; }
COMMON_METHODS
};
@@ -278,26 +355,29 @@ struct ExprLet : Expr
struct ExprWith : Expr
{
- Pos pos;
+ PosIdx pos;
Expr * attrs, * body;
size_t prevWith;
- ExprWith(const Pos & pos, Expr * attrs, Expr * body) : pos(pos), attrs(attrs), body(body) { };
+ ExprWith(const PosIdx & pos, Expr * attrs, Expr * body) : pos(pos), attrs(attrs), body(body) { };
+ PosIdx getPos() const override { return pos; }
COMMON_METHODS
};
struct ExprIf : Expr
{
- Pos pos;
+ PosIdx pos;
Expr * cond, * then, * else_;
- ExprIf(const Pos & pos, Expr * cond, Expr * then, Expr * else_) : pos(pos), cond(cond), then(then), else_(else_) { };
+ ExprIf(const PosIdx & pos, Expr * cond, Expr * then, Expr * else_) : pos(pos), cond(cond), then(then), else_(else_) { };
+ PosIdx getPos() const override { return pos; }
COMMON_METHODS
};
struct ExprAssert : Expr
{
- Pos pos;
+ PosIdx pos;
Expr * cond, * body;
- ExprAssert(const Pos & pos, Expr * cond, Expr * body) : pos(pos), cond(cond), body(body) { };
+ ExprAssert(const PosIdx & pos, Expr * cond, Expr * body) : pos(pos), cond(cond), body(body) { };
+ PosIdx getPos() const override { return pos; }
COMMON_METHODS
};
@@ -311,19 +391,20 @@ struct ExprOpNot : Expr
#define MakeBinOp(name, s) \
struct name : Expr \
{ \
- Pos pos; \
+ PosIdx pos; \
Expr * e1, * e2; \
name(Expr * e1, Expr * e2) : e1(e1), e2(e2) { }; \
- name(const Pos & pos, Expr * e1, Expr * e2) : pos(pos), e1(e1), e2(e2) { }; \
- void show(std::ostream & str) const \
+ name(const PosIdx & pos, Expr * e1, Expr * e2) : pos(pos), e1(e1), e2(e2) { }; \
+ void show(const SymbolTable & symbols, std::ostream & str) const override \
{ \
- str << "(" << *e1 << " " s " " << *e2 << ")"; \
+ str << "("; e1->show(symbols, str); str << " " s " "; e2->show(symbols, str); str << ")"; \
} \
- void bindVars(const StaticEnv & env) \
+ void bindVars(EvalState & es, const std::shared_ptr<const StaticEnv> & env) override \
{ \
- e1->bindVars(env); e2->bindVars(env); \
+ e1->bindVars(es, env); e2->bindVars(es, env); \
} \
- void eval(EvalState & state, Env & env, Value & v); \
+ void eval(EvalState & state, Env & env, Value & v) override; \
+ PosIdx getPos() const override { return pos; } \
};
MakeBinOp(ExprOpEq, "==")
@@ -336,18 +417,20 @@ MakeBinOp(ExprOpConcatLists, "++")
struct ExprConcatStrings : Expr
{
- Pos pos;
+ PosIdx pos;
bool forceString;
- std::vector<std::pair<Pos, Expr *> > * es;
- ExprConcatStrings(const Pos & pos, bool forceString, std::vector<std::pair<Pos, Expr *> > * es)
+ std::vector<std::pair<PosIdx, Expr *>> * es;
+ ExprConcatStrings(const PosIdx & pos, bool forceString, std::vector<std::pair<PosIdx, Expr *>> * es)
: pos(pos), forceString(forceString), es(es) { };
+ PosIdx getPos() const override { return pos; }
COMMON_METHODS
};
struct ExprPos : Expr
{
- Pos pos;
- ExprPos(const Pos & pos) : pos(pos) { };
+ PosIdx pos;
+ ExprPos(const PosIdx & pos) : pos(pos) { };
+ PosIdx getPos() const override { return pos; }
COMMON_METHODS
};
@@ -385,7 +468,7 @@ struct StaticEnv
vars.erase(it, end);
}
- Vars::const_iterator find(const Symbol & name) const
+ Vars::const_iterator find(Symbol name) const
{
Vars::value_type key(name, 0);
auto i = std::lower_bound(vars.begin(), vars.end(), key);
diff --git a/src/libexpr/parser.y b/src/libexpr/parser.y
index 919b9cfae..7c9b5a2db 100644
--- a/src/libexpr/parser.y
+++ b/src/libexpr/parser.y
@@ -32,12 +32,12 @@ namespace nix {
SymbolTable & symbols;
Expr * result;
Path basePath;
- Symbol file;
- FileOrigin origin;
+ PosTable::Origin origin;
std::optional<ErrorInfo> error;
- ParseData(EvalState & state)
+ ParseData(EvalState & state, PosTable::Origin origin)
: state(state)
, symbols(state.symbols)
+ , origin(std::move(origin))
{ };
};
@@ -77,26 +77,26 @@ using namespace nix;
namespace nix {
-static void dupAttr(const AttrPath & attrPath, const Pos & pos, const Pos & prevPos)
+static void dupAttr(const EvalState & state, const AttrPath & attrPath, const PosIdx pos, const PosIdx prevPos)
{
throw ParseError({
.msg = hintfmt("attribute '%1%' already defined at %2%",
- showAttrPath(attrPath), prevPos),
- .errPos = pos
+ showAttrPath(state.symbols, attrPath), state.positions[prevPos]),
+ .errPos = state.positions[pos]
});
}
-static void dupAttr(Symbol attr, const Pos & pos, const Pos & prevPos)
+static void dupAttr(const EvalState & state, Symbol attr, const PosIdx pos, const PosIdx prevPos)
{
throw ParseError({
- .msg = hintfmt("attribute '%1%' already defined at %2%", attr, prevPos),
- .errPos = pos
+ .msg = hintfmt("attribute '%1%' already defined at %2%", state.symbols[attr], state.positions[prevPos]),
+ .errPos = state.positions[pos]
});
}
static void addAttr(ExprAttrs * attrs, AttrPath & attrPath,
- Expr * e, const Pos & pos)
+ Expr * e, const PosIdx pos, const nix::EvalState & state)
{
AttrPath::iterator i;
// All attrpaths have at least one attr
@@ -104,15 +104,15 @@ static void addAttr(ExprAttrs * attrs, AttrPath & attrPath,
// Checking attrPath validity.
// ===========================
for (i = attrPath.begin(); i + 1 < attrPath.end(); i++) {
- if (i->symbol.set()) {
+ if (i->symbol) {
ExprAttrs::AttrDefs::iterator j = attrs->attrs.find(i->symbol);
if (j != attrs->attrs.end()) {
if (!j->second.inherited) {
ExprAttrs * attrs2 = dynamic_cast<ExprAttrs *>(j->second.e);
- if (!attrs2) dupAttr(attrPath, pos, j->second.pos);
+ if (!attrs2) dupAttr(state, attrPath, pos, j->second.pos);
attrs = attrs2;
} else
- dupAttr(attrPath, pos, j->second.pos);
+ dupAttr(state, attrPath, pos, j->second.pos);
} else {
ExprAttrs * nested = new ExprAttrs;
attrs->attrs[i->symbol] = ExprAttrs::AttrDef(nested, pos);
@@ -126,7 +126,7 @@ static void addAttr(ExprAttrs * attrs, AttrPath & attrPath,
}
// Expr insertion.
// ==========================
- if (i->symbol.set()) {
+ if (i->symbol) {
ExprAttrs::AttrDefs::iterator j = attrs->attrs.find(i->symbol);
if (j != attrs->attrs.end()) {
// This attr path is already defined. However, if both
@@ -139,11 +139,11 @@ static void addAttr(ExprAttrs * attrs, AttrPath & attrPath,
for (auto & ad : ae->attrs) {
auto j2 = jAttrs->attrs.find(ad.first);
if (j2 != jAttrs->attrs.end()) // Attr already defined in iAttrs, error.
- dupAttr(ad.first, j2->second.pos, ad.second.pos);
+ dupAttr(state, ad.first, j2->second.pos, ad.second.pos);
jAttrs->attrs.emplace(ad.first, ad.second);
}
} else {
- dupAttr(attrPath, pos, j->second.pos);
+ dupAttr(state, attrPath, pos, j->second.pos);
}
} else {
// This attr path is not defined. Let's create it.
@@ -157,14 +157,14 @@ static void addAttr(ExprAttrs * attrs, AttrPath & attrPath,
static Formals * toFormals(ParseData & data, ParserFormals * formals,
- Pos pos = noPos, Symbol arg = {})
+ PosIdx pos = noPos, Symbol arg = {})
{
std::sort(formals->formals.begin(), formals->formals.end(),
[] (const auto & a, const auto & b) {
return std::tie(a.name, a.pos) < std::tie(b.name, b.pos);
});
- std::optional<std::pair<Symbol, Pos>> duplicate;
+ std::optional<std::pair<Symbol, PosIdx>> duplicate;
for (size_t i = 0; i + 1 < formals->formals.size(); i++) {
if (formals->formals[i].name != formals->formals[i + 1].name)
continue;
@@ -173,18 +173,18 @@ static Formals * toFormals(ParseData & data, ParserFormals * formals,
}
if (duplicate)
throw ParseError({
- .msg = hintfmt("duplicate formal function argument '%1%'", duplicate->first),
- .errPos = duplicate->second
+ .msg = hintfmt("duplicate formal function argument '%1%'", data.symbols[duplicate->first]),
+ .errPos = data.state.positions[duplicate->second]
});
Formals result;
result.ellipsis = formals->ellipsis;
result.formals = std::move(formals->formals);
- if (arg.set() && result.has(arg))
+ if (arg && result.has(arg))
throw ParseError({
- .msg = hintfmt("duplicate formal function argument '%1%'", arg),
- .errPos = pos
+ .msg = hintfmt("duplicate formal function argument '%1%'", data.symbols[arg]),
+ .errPos = data.state.positions[pos]
});
delete formals;
@@ -192,8 +192,8 @@ static Formals * toFormals(ParseData & data, ParserFormals * formals,
}
-static Expr * stripIndentation(const Pos & pos, SymbolTable & symbols,
- std::vector<std::pair<Pos, std::variant<Expr *, StringToken> > > & es)
+static Expr * stripIndentation(const PosIdx pos, SymbolTable & symbols,
+ std::vector<std::pair<PosIdx, std::variant<Expr *, StringToken>>> & es)
{
if (es.empty()) return new ExprString("");
@@ -233,7 +233,7 @@ static Expr * stripIndentation(const Pos & pos, SymbolTable & symbols,
}
/* Strip spaces from each line. */
- std::vector<std::pair<Pos, Expr *> > * es2 = new std::vector<std::pair<Pos, Expr *> >;
+ auto * es2 = new std::vector<std::pair<PosIdx, Expr *>>;
atStartOfLine = true;
size_t curDropped = 0;
size_t n = es.size();
@@ -284,9 +284,9 @@ static Expr * stripIndentation(const Pos & pos, SymbolTable & symbols,
}
-static inline Pos makeCurPos(const YYLTYPE & loc, ParseData * data)
+static inline PosIdx makeCurPos(const YYLTYPE & loc, ParseData * data)
{
- return Pos(data->origin, data->file, loc.first_line, loc.first_column);
+ return data->state.positions.add(data->origin, loc.first_line, loc.first_column);
}
#define CUR_POS makeCurPos(*yylocp, data)
@@ -299,7 +299,7 @@ void yyerror(YYLTYPE * loc, yyscan_t scanner, ParseData * data, const char * err
{
data->error = {
.msg = hintfmt(error),
- .errPos = makeCurPos(*loc, data)
+ .errPos = data->state.positions[makeCurPos(*loc, data)]
};
}
@@ -320,8 +320,8 @@ void yyerror(YYLTYPE * loc, yyscan_t scanner, ParseData * data, const char * err
StringToken uri;
StringToken str;
std::vector<nix::AttrName> * attrNames;
- std::vector<std::pair<nix::Pos, nix::Expr *> > * string_parts;
- std::vector<std::pair<nix::Pos, std::variant<nix::Expr *, StringToken> > > * ind_string_parts;
+ std::vector<std::pair<nix::PosIdx, nix::Expr *>> * string_parts;
+ std::vector<std::pair<nix::PosIdx, std::variant<nix::Expr *, StringToken>>> * ind_string_parts;
}
%type <e> start expr expr_function expr_if expr_op
@@ -369,15 +369,15 @@ expr_function
: ID ':' expr_function
{ $$ = new ExprLambda(CUR_POS, data->symbols.create($1), 0, $3); }
| '{' formals '}' ':' expr_function
- { $$ = new ExprLambda(CUR_POS, data->symbols.create(""), toFormals(*data, $2), $5); }
+ { $$ = new ExprLambda(CUR_POS, toFormals(*data, $2), $5); }
| '{' formals '}' '@' ID ':' expr_function
{
- Symbol arg = data->symbols.create($5);
+ auto arg = data->symbols.create($5);
$$ = new ExprLambda(CUR_POS, arg, toFormals(*data, $2, CUR_POS, arg), $7);
}
| ID '@' '{' formals '}' ':' expr_function
{
- Symbol arg = data->symbols.create($1);
+ auto arg = data->symbols.create($1);
$$ = new ExprLambda(CUR_POS, arg, toFormals(*data, $4, CUR_POS, arg), $7);
}
| ASSERT expr ';' expr_function
@@ -388,7 +388,7 @@ expr_function
{ if (!$2->dynamicAttrs.empty())
throw ParseError({
.msg = hintfmt("dynamic attributes not allowed in let"),
- .errPos = CUR_POS
+ .errPos = data->state.positions[CUR_POS]
});
$$ = new ExprLet($2, $4);
}
@@ -415,7 +415,7 @@ expr_op
| expr_op UPDATE expr_op { $$ = new ExprOpUpdate(CUR_POS, $1, $3); }
| expr_op '?' attrpath { $$ = new ExprOpHasAttr($1, *$3); }
| expr_op '+' expr_op
- { $$ = new ExprConcatStrings(CUR_POS, false, new std::vector<std::pair<Pos, Expr *> >({{makeCurPos(@1, data), $1}, {makeCurPos(@3, data), $3}})); }
+ { $$ = new ExprConcatStrings(CUR_POS, false, new std::vector<std::pair<PosIdx, Expr *>>({{makeCurPos(@1, data), $1}, {makeCurPos(@3, data), $3}})); }
| expr_op '-' expr_op { $$ = new ExprCall(CUR_POS, new ExprVar(data->symbols.create("__sub")), {$1, $3}); }
| expr_op '*' expr_op { $$ = new ExprCall(CUR_POS, new ExprVar(data->symbols.create("__mul")), {$1, $3}); }
| expr_op '/' expr_op { $$ = new ExprCall(CUR_POS, new ExprVar(data->symbols.create("__div")), {$1, $3}); }
@@ -477,7 +477,7 @@ expr_simple
if (noURLLiterals)
throw ParseError({
.msg = hintfmt("URL literals are disabled"),
- .errPos = CUR_POS
+ .errPos = data->state.positions[CUR_POS]
});
$$ = new ExprString(std::string($1));
}
@@ -503,9 +503,9 @@ string_parts_interpolated
: string_parts_interpolated STR
{ $$ = $1; $1->emplace_back(makeCurPos(@2, data), new ExprString(std::string($2))); }
| string_parts_interpolated DOLLAR_CURLY expr '}' { $$ = $1; $1->emplace_back(makeCurPos(@2, data), $3); }
- | DOLLAR_CURLY expr '}' { $$ = new std::vector<std::pair<Pos, Expr *> >; $$->emplace_back(makeCurPos(@1, data), $2); }
+ | DOLLAR_CURLY expr '}' { $$ = new std::vector<std::pair<PosIdx, Expr *>>; $$->emplace_back(makeCurPos(@1, data), $2); }
| STR DOLLAR_CURLY expr '}' {
- $$ = new std::vector<std::pair<Pos, Expr *> >;
+ $$ = new std::vector<std::pair<PosIdx, Expr *>>;
$$->emplace_back(makeCurPos(@1, data), new ExprString(std::string($1)));
$$->emplace_back(makeCurPos(@2, data), $3);
}
@@ -520,6 +520,12 @@ path_start
$$ = new ExprPath(path);
}
| HPATH {
+ if (evalSettings.pureEval) {
+ throw Error(
+ "the path '%s' can not be resolved in pure mode",
+ std::string_view($1.p, $1.l)
+ );
+ }
Path path(getHome() + std::string($1.p + 1, $1.l - 1));
$$ = new ExprPath(path);
}
@@ -528,17 +534,17 @@ path_start
ind_string_parts
: ind_string_parts IND_STR { $$ = $1; $1->emplace_back(makeCurPos(@2, data), $2); }
| ind_string_parts DOLLAR_CURLY expr '}' { $$ = $1; $1->emplace_back(makeCurPos(@2, data), $3); }
- | { $$ = new std::vector<std::pair<Pos, std::variant<Expr *, StringToken> > >; }
+ | { $$ = new std::vector<std::pair<PosIdx, std::variant<Expr *, StringToken>>>; }
;
binds
- : binds attrpath '=' expr ';' { $$ = $1; addAttr($$, *$2, $4, makeCurPos(@2, data)); }
+ : binds attrpath '=' expr ';' { $$ = $1; addAttr($$, *$2, $4, makeCurPos(@2, data), data->state); }
| binds INHERIT attrs ';'
{ $$ = $1;
for (auto & i : *$3) {
if ($$->attrs.find(i.symbol) != $$->attrs.end())
- dupAttr(i.symbol, makeCurPos(@3, data), $$->attrs[i.symbol].pos);
- Pos pos = makeCurPos(@3, data);
+ dupAttr(data->state, i.symbol, makeCurPos(@3, data), $$->attrs[i.symbol].pos);
+ auto pos = makeCurPos(@3, data);
$$->attrs.emplace(i.symbol, ExprAttrs::AttrDef(new ExprVar(CUR_POS, i.symbol), pos, true));
}
}
@@ -547,7 +553,7 @@ binds
/* !!! Should ensure sharing of the expression in $4. */
for (auto & i : *$6) {
if ($$->attrs.find(i.symbol) != $$->attrs.end())
- dupAttr(i.symbol, makeCurPos(@6, data), $$->attrs[i.symbol].pos);
+ dupAttr(data->state, i.symbol, makeCurPos(@6, data), $$->attrs[i.symbol].pos);
$$->attrs.emplace(i.symbol, ExprAttrs::AttrDef(new ExprSelect(CUR_POS, $4, i.symbol), makeCurPos(@6, data)));
}
}
@@ -565,7 +571,7 @@ attrs
} else
throw ParseError({
.msg = hintfmt("dynamic attributes not allowed in inherit"),
- .errPos = makeCurPos(@2, data)
+ .errPos = data->state.positions[makeCurPos(@2, data)]
});
}
| { $$ = new AttrPath; }
@@ -621,8 +627,8 @@ formals
;
formal
- : ID { $$ = new Formal(CUR_POS, data->symbols.create($1), 0); }
- | ID '?' expr { $$ = new Formal(CUR_POS, data->symbols.create($1), $3); }
+ : ID { $$ = new Formal{CUR_POS, data->symbols.create($1), 0}; }
+ | ID '?' expr { $$ = new Formal{CUR_POS, data->symbols.create($1), $3}; }
;
%%
@@ -643,22 +649,22 @@ namespace nix {
Expr * EvalState::parse(char * text, size_t length, FileOrigin origin,
- const PathView path, const PathView basePath, StaticEnv & staticEnv)
+ const PathView path, const PathView basePath, std::shared_ptr<StaticEnv> & staticEnv)
{
yyscan_t scanner;
- ParseData data(*this);
- data.origin = origin;
+ std::string file;
switch (origin) {
case foFile:
- data.file = data.symbols.create(path);
+ file = path;
break;
case foStdin:
case foString:
- data.file = data.symbols.create(text);
+ file = text;
break;
default:
assert(false);
}
+ ParseData data(*this, {file, origin});
data.basePath = basePath;
yylex_init(&scanner);
@@ -668,7 +674,7 @@ Expr * EvalState::parse(char * text, size_t length, FileOrigin origin,
if (res) throw ParseError(data.error.value());
- data.result->bindVars(staticEnv);
+ data.result->bindVars(*this, staticEnv);
return data.result;
}
@@ -706,7 +712,7 @@ Expr * EvalState::parseExprFromFile(const Path & path)
}
-Expr * EvalState::parseExprFromFile(const Path & path, StaticEnv & staticEnv)
+Expr * EvalState::parseExprFromFile(const Path & path, std::shared_ptr<StaticEnv> & staticEnv)
{
auto buffer = readFile(path);
// readFile should have left some extra space for terminators
@@ -715,7 +721,7 @@ Expr * EvalState::parseExprFromFile(const Path & path, StaticEnv & staticEnv)
}
-Expr * EvalState::parseExprFromString(std::string s, const Path & basePath, StaticEnv & staticEnv)
+Expr * EvalState::parseExprFromString(std::string s, const Path & basePath, std::shared_ptr<StaticEnv> & staticEnv)
{
s.append("\0\0", 2);
return parse(s.data(), s.size(), foString, "", basePath, staticEnv);
@@ -760,7 +766,7 @@ Path EvalState::findFile(const std::string_view path)
}
-Path EvalState::findFile(SearchPath & searchPath, const std::string_view path, const Pos & pos)
+Path EvalState::findFile(SearchPath & searchPath, const std::string_view path, const PosIdx pos)
{
for (auto & i : searchPath) {
std::string suffix;
@@ -782,13 +788,13 @@ Path EvalState::findFile(SearchPath & searchPath, const std::string_view path, c
if (hasPrefix(path, "nix/"))
return concatStrings(corepkgsPrefix, path.substr(4));
- throw ThrownError({
+ debugThrowLastTrace(ThrownError({
.msg = hintfmt(evalSettings.pureEval
? "cannot look up '<%s>' in pure evaluation mode (use '--impure' to override)"
: "file '%s' was not found in the Nix search path (add it using $NIX_PATH or -I)",
path),
- .errPos = pos
- });
+ .errPos = positions[pos]
+ }));
}
diff --git a/src/libexpr/primops.cc b/src/libexpr/primops.cc
index aa22c3b61..840bfecef 100644
--- a/src/libexpr/primops.cc
+++ b/src/libexpr/primops.cc
@@ -43,10 +43,10 @@ StringMap EvalState::realiseContext(const PathSet & context)
StringMap res;
for (auto & i : context) {
- auto [ctxS, outputName] = decodeContext(i);
- auto ctx = store->parseStorePath(ctxS);
+ auto [ctx, outputName] = decodeContext(*store, i);
+ auto ctxS = store->printStorePath(ctx);
if (!store->isValidPath(ctx))
- throw InvalidPathError(store->printStorePath(ctx));
+ debugThrowLastTrace(InvalidPathError(store->printStorePath(ctx)));
if (!outputName.empty() && ctx.isDerivation()) {
drvs.push_back({ctx, {outputName}});
} else {
@@ -57,9 +57,9 @@ StringMap EvalState::realiseContext(const PathSet & context)
if (drvs.empty()) return {};
if (!evalSettings.enableImportFromDerivation)
- throw Error(
+ debugThrowLastTrace(Error(
"cannot build '%1%' during evaluation because the option 'allow-import-from-derivation' is disabled",
- store->printStorePath(drvs.begin()->drvPath));
+ store->printStorePath(drvs.begin()->drvPath)));
/* Build/substitute the context. */
std::vector<DerivedPath> buildReqs;
@@ -68,14 +68,15 @@ StringMap EvalState::realiseContext(const PathSet & context)
/* Get all the output paths corresponding to the placeholders we had */
for (auto & [drvPath, outputs] : drvs) {
- auto outputPaths = store->queryDerivationOutputMap(drvPath);
+ const auto outputPaths = store->queryDerivationOutputMap(drvPath);
for (auto & outputName : outputs) {
- if (outputPaths.count(outputName) == 0)
- throw Error("derivation '%s' does not have an output named '%s'",
- store->printStorePath(drvPath), outputName);
+ auto outputPath = get(outputPaths, outputName);
+ if (!outputPath)
+ debugThrowLastTrace(Error("derivation '%s' does not have an output named '%s'",
+ store->printStorePath(drvPath), outputName));
res.insert_or_assign(
downstreamPlaceholder(*store, drvPath, outputName),
- store->printStorePath(outputPaths.at(outputName))
+ store->printStorePath(*outputPath)
);
}
}
@@ -96,7 +97,7 @@ struct RealisePathFlags {
bool checkForPureEval = true;
};
-static Path realisePath(EvalState & state, const Pos & pos, Value & v, const RealisePathFlags flags = {})
+static Path realisePath(EvalState & state, const PosIdx pos, Value & v, const RealisePathFlags flags = {})
{
PathSet context;
@@ -105,7 +106,7 @@ static Path realisePath(EvalState & state, const Pos & pos, Value & v, const Rea
try {
return state.coerceToPath(pos, v, context);
} catch (Error & e) {
- e.addTrace(pos, "while realising the context of a path");
+ e.addTrace(state.positions[pos], "while realising the context of a path");
throw;
}
}();
@@ -119,7 +120,7 @@ static Path realisePath(EvalState & state, const Pos & pos, Value & v, const Rea
? state.checkSourcePath(realPath)
: realPath;
} catch (Error & e) {
- e.addTrace(pos, "while realising the context of path '%s'", path);
+ e.addTrace(state.positions[pos], "while realising the context of path '%s'", path);
throw;
}
}
@@ -157,7 +158,7 @@ static void mkOutputString(
/* Load and evaluate an expression from path specified by the
argument. */
-static void import(EvalState & state, const Pos & pos, Value & vPath, Value * vScope, Value & v)
+static void import(EvalState & state, const PosIdx pos, Value & vPath, Value * vScope, Value & v)
{
auto path = realisePath(state, pos, vPath);
@@ -215,11 +216,11 @@ static void import(EvalState & state, const Pos & pos, Value & vPath, Value * vS
Env * env = &state.allocEnv(vScope->attrs->size());
env->up = &state.baseEnv;
- StaticEnv staticEnv(false, &state.staticBaseEnv, vScope->attrs->size());
+ auto staticEnv = std::make_shared<StaticEnv>(false, state.staticBaseEnv.get(), vScope->attrs->size());
unsigned int displ = 0;
for (auto & attr : *vScope->attrs) {
- staticEnv.vars.emplace_back(attr.name, displ);
+ staticEnv->vars.emplace_back(attr.name, displ);
env->values[displ++] = attr.value;
}
@@ -237,7 +238,7 @@ static void import(EvalState & state, const Pos & pos, Value & vPath, Value * vS
static RegisterPrimOp primop_scopedImport(RegisterPrimOp::Info {
.name = "scopedImport",
.arity = 2,
- .fun = [](EvalState & state, const Pos & pos, Value * * args, Value & v)
+ .fun = [](EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
import(state, pos, *args[1], args[0], v);
}
@@ -299,7 +300,7 @@ static RegisterPrimOp primop_import({
(The function argument doesn’t have to be called `x` in `foo.nix`;
any name would work.)
)",
- .fun = [](EvalState & state, const Pos & pos, Value * * args, Value & v)
+ .fun = [](EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
import(state, pos, *args[0], nullptr, v);
}
@@ -310,7 +311,7 @@ static RegisterPrimOp primop_import({
extern "C" typedef void (*ValueInitializer)(EvalState & state, Value & v);
/* Load a ValueInitializer from a DSO and return whatever it initializes */
-void prim_importNative(EvalState & state, const Pos & pos, Value * * args, Value & v)
+void prim_importNative(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
auto path = realisePath(state, pos, *args[0]);
@@ -318,17 +319,16 @@ void prim_importNative(EvalState & state, const Pos & pos, Value * * args, Value
void *handle = dlopen(path.c_str(), RTLD_LAZY | RTLD_LOCAL);
if (!handle)
- throw EvalError("could not open '%1%': %2%", path, dlerror());
+ state.debugThrowLastTrace(EvalError("could not open '%1%': %2%", path, dlerror()));
dlerror();
ValueInitializer func = (ValueInitializer) dlsym(handle, sym.c_str());
if(!func) {
char *message = dlerror();
if (message)
- throw EvalError("could not load symbol '%1%' from '%2%': %3%", sym, path, message);
+ state.debugThrowLastTrace(EvalError("could not load symbol '%1%' from '%2%': %3%", sym, path, message));
else
- throw EvalError("symbol '%1%' from '%2%' resolved to NULL when a function pointer was expected",
- sym, path);
+ state.debugThrowLastTrace(EvalError("symbol '%1%' from '%2%' resolved to NULL when a function pointer was expected", sym, path));
}
(func)(state, v);
@@ -338,17 +338,16 @@ void prim_importNative(EvalState & state, const Pos & pos, Value * * args, Value
/* Execute a program and parse its output */
-void prim_exec(EvalState & state, const Pos & pos, Value * * args, Value & v)
+void prim_exec(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
state.forceList(*args[0], pos);
auto elems = args[0]->listElems();
auto count = args[0]->listSize();
- if (count == 0) {
- throw EvalError({
+ if (count == 0)
+ state.debugThrowLastTrace(EvalError({
.msg = hintfmt("at least one argument to 'exec' required"),
- .errPos = pos
- });
- }
+ .errPos = state.positions[pos]
+ }));
PathSet context;
auto program = state.coerceToString(pos, *elems[0], context, false, false).toOwned();
Strings commandArgs;
@@ -358,32 +357,33 @@ void prim_exec(EvalState & state, const Pos & pos, Value * * args, Value & v)
try {
auto _ = state.realiseContext(context); // FIXME: Handle CA derivations
} catch (InvalidPathError & e) {
- throw EvalError({
+ state.debugThrowLastTrace(EvalError({
.msg = hintfmt("cannot execute '%1%', since path '%2%' is not valid",
program, e.path),
- .errPos = pos
- });
+ .errPos = state.positions[pos]
+ }));
}
auto output = runProgram(program, true, commandArgs);
Expr * parsed;
try {
- parsed = state.parseExprFromString(std::move(output), pos.file);
+ auto base = state.positions[pos];
+ parsed = state.parseExprFromString(std::move(output), base.file);
} catch (Error & e) {
- e.addTrace(pos, "While parsing the output from '%1%'", program);
+ e.addTrace(state.positions[pos], "While parsing the output from '%1%'", program);
throw;
}
try {
state.eval(parsed, v);
} catch (Error & e) {
- e.addTrace(pos, "While evaluating the output from '%1%'", program);
+ e.addTrace(state.positions[pos], "While evaluating the output from '%1%'", program);
throw;
}
}
/* Return a string representing the type of the expression. */
-static void prim_typeOf(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_typeOf(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
state.forceValue(*args[0], pos);
std::string t;
@@ -402,7 +402,7 @@ static void prim_typeOf(EvalState & state, const Pos & pos, Value * * args, Valu
case nFloat: t = "float"; break;
case nThunk: abort();
}
- v.mkString(state.symbols.create(t));
+ v.mkString(t);
}
static RegisterPrimOp primop_typeOf({
@@ -417,7 +417,7 @@ static RegisterPrimOp primop_typeOf({
});
/* Determine whether the argument is the null value. */
-static void prim_isNull(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_isNull(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
state.forceValue(*args[0], pos);
v.mkBool(args[0]->type() == nNull);
@@ -437,7 +437,7 @@ static RegisterPrimOp primop_isNull({
});
/* Determine whether the argument is a function. */
-static void prim_isFunction(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_isFunction(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
state.forceValue(*args[0], pos);
v.mkBool(args[0]->type() == nFunction);
@@ -453,7 +453,7 @@ static RegisterPrimOp primop_isFunction({
});
/* Determine whether the argument is an integer. */
-static void prim_isInt(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_isInt(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
state.forceValue(*args[0], pos);
v.mkBool(args[0]->type() == nInt);
@@ -469,7 +469,7 @@ static RegisterPrimOp primop_isInt({
});
/* Determine whether the argument is a float. */
-static void prim_isFloat(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_isFloat(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
state.forceValue(*args[0], pos);
v.mkBool(args[0]->type() == nFloat);
@@ -485,7 +485,7 @@ static RegisterPrimOp primop_isFloat({
});
/* Determine whether the argument is a string. */
-static void prim_isString(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_isString(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
state.forceValue(*args[0], pos);
v.mkBool(args[0]->type() == nString);
@@ -501,7 +501,7 @@ static RegisterPrimOp primop_isString({
});
/* Determine whether the argument is a Boolean. */
-static void prim_isBool(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_isBool(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
state.forceValue(*args[0], pos);
v.mkBool(args[0]->type() == nBool);
@@ -517,7 +517,7 @@ static RegisterPrimOp primop_isBool({
});
/* Determine whether the argument is a path. */
-static void prim_isPath(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_isPath(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
state.forceValue(*args[0], pos);
v.mkBool(args[0]->type() == nPath);
@@ -545,7 +545,7 @@ struct CompareValues
if (v1->type() == nInt && v2->type() == nFloat)
return v1->integer < v2->fpoint;
if (v1->type() != v2->type())
- throw EvalError("cannot compare %1% with %2%", showType(*v1), showType(*v2));
+ state.debugThrowLastTrace(EvalError("cannot compare %1% with %2%", showType(*v1), showType(*v2)));
switch (v1->type()) {
case nInt:
return v1->integer < v2->integer;
@@ -567,14 +567,14 @@ struct CompareValues
}
}
default:
- throw EvalError("cannot compare %1% with %2%", showType(*v1), showType(*v2));
+ state.debugThrowLastTrace(EvalError("cannot compare %1% with %2%", showType(*v1), showType(*v2)));
}
}
};
#if HAVE_BOEHMGC
-typedef std::list<Value *, gc_allocator<Value *> > ValueList;
+typedef std::list<Value *, gc_allocator<Value *>> ValueList;
#else
typedef std::list<Value *> ValueList;
#endif
@@ -585,39 +585,39 @@ static Bindings::iterator getAttr(
std::string_view funcName,
Symbol attrSym,
Bindings * attrSet,
- const Pos & pos)
+ const PosIdx pos)
{
Bindings::iterator value = attrSet->find(attrSym);
if (value == attrSet->end()) {
hintformat errorMsg = hintfmt(
"attribute '%s' missing for call to '%s'",
- attrSym,
+ state.symbols[attrSym],
funcName
);
- Pos aPos = *attrSet->pos;
- if (aPos == noPos) {
- throw TypeError({
+ auto aPos = attrSet->pos;
+ if (!aPos) {
+ state.debugThrowLastTrace(TypeError({
.msg = errorMsg,
- .errPos = pos,
- });
+ .errPos = state.positions[pos],
+ }));
} else {
auto e = TypeError({
.msg = errorMsg,
- .errPos = aPos,
+ .errPos = state.positions[aPos],
});
// Adding another trace for the function name to make it clear
// which call received wrong arguments.
- e.addTrace(pos, hintfmt("while invoking '%s'", funcName));
- throw e;
+ e.addTrace(state.positions[pos], hintfmt("while invoking '%s'", funcName));
+ state.debugThrowLastTrace(e);
}
}
return value;
}
-static void prim_genericClosure(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_genericClosure(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
state.forceAttrs(*args[0], pos);
@@ -664,10 +664,10 @@ static void prim_genericClosure(EvalState & state, const Pos & pos, Value * * ar
Bindings::iterator key =
e->attrs->find(state.sKey);
if (key == e->attrs->end())
- throw EvalError({
+ state.debugThrowLastTrace(EvalError({
.msg = hintfmt("attribute 'key' required"),
- .errPos = pos
- });
+ .errPos = state.positions[pos]
+ }));
state.forceValue(*key->value, pos);
if (!doneKeys.insert(key->value).second) continue;
@@ -694,21 +694,81 @@ static void prim_genericClosure(EvalState & state, const Pos & pos, Value * * ar
static RegisterPrimOp primop_genericClosure(RegisterPrimOp::Info {
.name = "__genericClosure",
+ .args = {"attrset"},
.arity = 1,
+ .doc = R"(
+ Take an *attrset* with values named `startSet` and `operator` in order to
+ return a *list of attrsets* by starting with the `startSet`, recursively
+ applying the `operator` function to each element. The *attrsets* in the
+ `startSet` and produced by the `operator` must each contain value named
+ `key` which are comparable to each other. The result is produced by
+ repeatedly calling the operator for each element encountered with a
+ unique key, terminating when no new elements are produced. For example,
+
+ ```
+ builtins.genericClosure {
+ startSet = [ {key = 5;} ];
+ operator = item: [{
+ key = if (item.key / 2 ) * 2 == item.key
+ then item.key / 2
+ else 3 * item.key + 1;
+ }];
+ }
+ ```
+ evaluates to
+ ```
+ [ { key = 5; } { key = 16; } { key = 8; } { key = 4; } { key = 2; } { key = 1; } ]
+ ```
+ )",
.fun = prim_genericClosure,
});
+
+static RegisterPrimOp primop_break({
+ .name = "break",
+ .args = {"v"},
+ .doc = R"(
+ In debug mode (enabled using `--debugger`), pause Nix expression evaluation and enter the REPL.
+ Otherwise, return the argument `v`.
+ )",
+ .fun = [](EvalState & state, const PosIdx pos, Value * * args, Value & v)
+ {
+ if (state.debugRepl && !state.debugTraces.empty()) {
+ auto error = Error(ErrorInfo {
+ .level = lvlInfo,
+ .msg = hintfmt("breakpoint reached"),
+ .errPos = state.positions[pos],
+ });
+
+ auto & dt = state.debugTraces.front();
+ state.runDebugRepl(&error, dt.env, dt.expr);
+
+ if (state.debugQuit) {
+ // If the user elects to quit the repl, throw an exception.
+ throw Error(ErrorInfo{
+ .level = lvlInfo,
+ .msg = hintfmt("quit the debugger"),
+ .errPos = state.positions[noPos],
+ });
+ }
+ }
+
+ // Return the value we were passed.
+ v = *args[0];
+ }
+});
+
static RegisterPrimOp primop_abort({
.name = "abort",
.args = {"s"},
.doc = R"(
Abort Nix expression evaluation and print the error message *s*.
)",
- .fun = [](EvalState & state, const Pos & pos, Value * * args, Value & v)
+ .fun = [](EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
PathSet context;
auto s = state.coerceToString(pos, *args[0], context).toOwned();
- throw Abort("evaluation aborted with the following error message: '%1%'", s);
+ state.debugThrowLastTrace(Abort("evaluation aborted with the following error message: '%1%'", s));
}
});
@@ -722,15 +782,15 @@ static RegisterPrimOp primop_throw({
derivations, a derivation that throws an error is silently skipped
(which is not the case for `abort`).
)",
- .fun = [](EvalState & state, const Pos & pos, Value * * args, Value & v)
+ .fun = [](EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
PathSet context;
auto s = state.coerceToString(pos, *args[0], context).toOwned();
- throw ThrownError(s);
+ state.debugThrowLastTrace(ThrownError(s));
}
});
-static void prim_addErrorContext(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_addErrorContext(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
try {
state.forceValue(*args[1], pos);
@@ -748,7 +808,7 @@ static RegisterPrimOp primop_addErrorContext(RegisterPrimOp::Info {
.fun = prim_addErrorContext,
});
-static void prim_ceil(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_ceil(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
auto value = state.forceFloat(*args[0], args[0]->determinePos(pos));
v.mkInt(ceil(value));
@@ -767,7 +827,7 @@ static RegisterPrimOp primop_ceil({
.fun = prim_ceil,
});
-static void prim_floor(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_floor(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
auto value = state.forceFloat(*args[0], args[0]->determinePos(pos));
v.mkInt(floor(value));
@@ -788,9 +848,21 @@ static RegisterPrimOp primop_floor({
/* Try evaluating the argument. Success => {success=true; value=something;},
* else => {success=false; value=false;} */
-static void prim_tryEval(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_tryEval(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
auto attrs = state.buildBindings(2);
+
+ /* increment state.trylevel, and decrement it when this function returns. */
+ MaintainCount trylevel(state.trylevel);
+
+ void (* savedDebugRepl)(ref<EvalState> es, const ValMap & extraEnv) = nullptr;
+ if (state.debugRepl && evalSettings.ignoreExceptionsDuringTry)
+ {
+ /* to prevent starting the repl from exceptions withing a tryEval, null it. */
+ savedDebugRepl = state.debugRepl;
+ state.debugRepl = nullptr;
+ }
+
try {
state.forceValue(*args[0], pos);
attrs.insert(state.sValue, args[0]);
@@ -799,6 +871,11 @@ static void prim_tryEval(EvalState & state, const Pos & pos, Value * * args, Val
attrs.alloc(state.sValue).mkBool(false);
attrs.alloc("success").mkBool(false);
}
+
+ // restore the debugRepl pointer if we saved it earlier.
+ if (savedDebugRepl)
+ state.debugRepl = savedDebugRepl;
+
v.mkAttrs(attrs);
}
@@ -824,7 +901,7 @@ static RegisterPrimOp primop_tryEval({
});
/* Return an environment variable. Use with care. */
-static void prim_getEnv(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_getEnv(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
std::string name(state.forceStringNoCtx(*args[0], pos));
v.mkString(evalSettings.restrictEval || evalSettings.pureEval ? "" : getEnv(name).value_or(""));
@@ -848,7 +925,7 @@ static RegisterPrimOp primop_getEnv({
});
/* Evaluate the first argument, then return the second argument. */
-static void prim_seq(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_seq(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
state.forceValue(*args[0], pos);
state.forceValue(*args[1], pos);
@@ -867,7 +944,7 @@ static RegisterPrimOp primop_seq({
/* Evaluate the first argument deeply (i.e. recursing into lists and
attrsets), then return the second argument. */
-static void prim_deepSeq(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_deepSeq(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
state.forceValueDeep(*args[0]);
state.forceValue(*args[1], pos);
@@ -887,13 +964,13 @@ static RegisterPrimOp primop_deepSeq({
/* Evaluate the first expression and print it on standard error. Then
return the second expression. Useful for debugging. */
-static void prim_trace(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_trace(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
state.forceValue(*args[0], pos);
if (args[0]->type() == nString)
printError("trace: %1%", args[0]->string.s);
else
- printError("trace: %1%", *args[0]);
+ printError("trace: %1%", printValue(state, *args[0]));
state.forceValue(*args[1], pos);
v = *args[1];
}
@@ -910,6 +987,15 @@ static RegisterPrimOp primop_trace({
});
+/* Takes two arguments and evaluates to the second one. Used as the
+ * builtins.traceVerbose implementation when --trace-verbose is not enabled
+ */
+static void prim_second(EvalState & state, const PosIdx pos, Value * * args, Value & v)
+{
+ state.forceValue(*args[1], pos);
+ v = *args[1];
+}
+
/*************************************************************
* Derivations
*************************************************************/
@@ -922,7 +1008,7 @@ static RegisterPrimOp primop_trace({
derivation; `drvPath' containing the path of the Nix expression;
and `type' set to `derivation' to indicate that this is a
derivation. */
-static void prim_derivationStrict(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_derivationStrict(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
state.forceAttrs(*args[0], pos);
@@ -936,11 +1022,11 @@ static void prim_derivationStrict(EvalState & state, const Pos & pos, Value * *
);
std::string drvName;
- Pos & posDrvName(*attr->pos);
+ const auto posDrvName = attr->pos;
try {
drvName = state.forceStringNoCtx(*attr->value, pos);
} catch (Error & e) {
- e.addTrace(posDrvName, "while evaluating the derivation attribute 'name'");
+ e.addTrace(state.positions[posDrvName], "while evaluating the derivation attribute 'name'");
throw;
}
@@ -964,53 +1050,54 @@ static void prim_derivationStrict(EvalState & state, const Pos & pos, Value * *
PathSet context;
bool contentAddressed = false;
+ bool isImpure = false;
std::optional<std::string> outputHash;
std::string outputHashAlgo;
- auto ingestionMethod = FileIngestionMethod::Flat;
+ std::optional<FileIngestionMethod> ingestionMethod;
StringSet outputs;
outputs.insert("out");
- for (auto & i : args[0]->attrs->lexicographicOrder()) {
+ for (auto & i : args[0]->attrs->lexicographicOrder(state.symbols)) {
if (i->name == state.sIgnoreNulls) continue;
- const std::string & key = i->name;
+ const std::string & key = state.symbols[i->name];
vomit("processing attribute '%1%'", key);
auto handleHashMode = [&](const std::string_view s) {
if (s == "recursive") ingestionMethod = FileIngestionMethod::Recursive;
else if (s == "flat") ingestionMethod = FileIngestionMethod::Flat;
else
- throw EvalError({
+ state.debugThrowLastTrace(EvalError({
.msg = hintfmt("invalid value '%s' for 'outputHashMode' attribute", s),
- .errPos = posDrvName
- });
+ .errPos = state.positions[posDrvName]
+ }));
};
auto handleOutputs = [&](const Strings & ss) {
outputs.clear();
for (auto & j : ss) {
if (outputs.find(j) != outputs.end())
- throw EvalError({
+ state.debugThrowLastTrace(EvalError({
.msg = hintfmt("duplicate derivation output '%1%'", j),
- .errPos = posDrvName
- });
+ .errPos = state.positions[posDrvName]
+ }));
/* !!! Check whether j is a valid attribute
name. */
/* Derivations cannot be named ‘drv’, because
then we'd have an attribute ‘drvPath’ in
the resulting set. */
if (j == "drv")
- throw EvalError({
+ state.debugThrowLastTrace(EvalError({
.msg = hintfmt("invalid derivation output name 'drv'" ),
- .errPos = posDrvName
- });
+ .errPos = state.positions[posDrvName]
+ }));
outputs.insert(j);
}
if (outputs.empty())
- throw EvalError({
+ state.debugThrowLastTrace(EvalError({
.msg = hintfmt("derivation cannot have an empty set of outputs"),
- .errPos = posDrvName
- });
+ .errPos = state.positions[posDrvName]
+ }));
};
try {
@@ -1026,6 +1113,12 @@ static void prim_derivationStrict(EvalState & state, const Pos & pos, Value * *
settings.requireExperimentalFeature(Xp::CaDerivations);
}
+ else if (i->name == state.sImpure) {
+ isImpure = state.forceBool(*i->value, pos);
+ if (isImpure)
+ settings.requireExperimentalFeature(Xp::ImpureDerivations);
+ }
+
/* The `args' attribute is special: it supplies the
command-line arguments to the builder. */
else if (i->name == state.sArgs) {
@@ -1067,7 +1160,7 @@ static void prim_derivationStrict(EvalState & state, const Pos & pos, Value * *
}
} else {
- auto s = state.coerceToString(*i->pos, *i->value, context, true).toOwned();
+ auto s = state.coerceToString(i->pos, *i->value, context, true).toOwned();
drv.env.emplace(key, s);
if (i->name == state.sBuilder) drv.builder = std::move(s);
else if (i->name == state.sSystem) drv.platform = std::move(s);
@@ -1081,7 +1174,7 @@ static void prim_derivationStrict(EvalState & state, const Pos & pos, Value * *
}
} catch (Error & e) {
- e.addTrace(posDrvName,
+ e.addTrace(state.positions[posDrvName],
"while evaluating the attribute '%1%' of the derivation '%2%'",
key, drvName);
throw;
@@ -1118,8 +1211,8 @@ static void prim_derivationStrict(EvalState & state, const Pos & pos, Value * *
/* Handle derivation outputs of the form ‘!<name>!<path>’. */
else if (path.at(0) == '!') {
- auto ctx = decodeContext(path);
- drv.inputDrvs[state.store->parseStorePath(ctx.first)].insert(ctx.second);
+ auto ctx = decodeContext(*state.store, path);
+ drv.inputDrvs[ctx.first].insert(ctx.second);
}
/* Otherwise it's a source file. */
@@ -1129,23 +1222,23 @@ static void prim_derivationStrict(EvalState & state, const Pos & pos, Value * *
/* Do we have all required attributes? */
if (drv.builder == "")
- throw EvalError({
+ state.debugThrowLastTrace(EvalError({
.msg = hintfmt("required attribute 'builder' missing"),
- .errPos = posDrvName
- });
+ .errPos = state.positions[posDrvName]
+ }));
if (drv.platform == "")
- throw EvalError({
+ state.debugThrowLastTrace(EvalError({
.msg = hintfmt("required attribute 'system' missing"),
- .errPos = posDrvName
- });
+ .errPos = state.positions[posDrvName]
+ }));
/* Check whether the derivation name is valid. */
if (isDerivation(drvName))
- throw EvalError({
+ state.debugThrowLastTrace(EvalError({
.msg = hintfmt("derivation names are not allowed to end in '%s'", drvExtension),
- .errPos = posDrvName
- });
+ .errPos = state.positions[posDrvName]
+ }));
if (outputHash) {
/* Handle fixed-output derivations.
@@ -1153,36 +1246,49 @@ static void prim_derivationStrict(EvalState & state, const Pos & pos, Value * *
Ignore `__contentAddressed` because fixed output derivations are
already content addressed. */
if (outputs.size() != 1 || *(outputs.begin()) != "out")
- throw Error({
+ state.debugThrowLastTrace(Error({
.msg = hintfmt("multiple outputs are not supported in fixed-output derivations"),
- .errPos = posDrvName
- });
+ .errPos = state.positions[posDrvName]
+ }));
- std::optional<HashType> ht = parseHashTypeOpt(outputHashAlgo);
- Hash h = newHashAllowEmpty(*outputHash, ht);
+ auto h = newHashAllowEmpty(*outputHash, parseHashTypeOpt(outputHashAlgo));
- auto outPath = state.store->makeFixedOutputPath(ingestionMethod, h, drvName);
+ auto method = ingestionMethod.value_or(FileIngestionMethod::Flat);
+ auto outPath = state.store->makeFixedOutputPath(method, h, drvName);
drv.env["out"] = state.store->printStorePath(outPath);
- drv.outputs.insert_or_assign("out", DerivationOutput {
- .output = DerivationOutputCAFixed {
- .hash = FixedOutputHash {
- .method = ingestionMethod,
- .hash = std::move(h),
- },
+ drv.outputs.insert_or_assign("out",
+ DerivationOutput::CAFixed {
+ .hash = FixedOutputHash {
+ .method = method,
+ .hash = std::move(h),
},
- });
+ });
}
- else if (contentAddressed) {
- HashType ht = parseHashType(outputHashAlgo);
+ else if (contentAddressed || isImpure) {
+ if (contentAddressed && isImpure)
+ throw EvalError({
+ .msg = hintfmt("derivation cannot be both content-addressed and impure"),
+ .errPos = state.positions[posDrvName]
+ });
+
+ auto ht = parseHashTypeOpt(outputHashAlgo).value_or(htSHA256);
+ auto method = ingestionMethod.value_or(FileIngestionMethod::Recursive);
+
for (auto & i : outputs) {
drv.env[i] = hashPlaceholder(i);
- drv.outputs.insert_or_assign(i, DerivationOutput {
- .output = DerivationOutputCAFloating {
- .method = ingestionMethod,
- .hashType = ht,
- },
- });
+ if (isImpure)
+ drv.outputs.insert_or_assign(i,
+ DerivationOutput::Impure {
+ .method = method,
+ .hashType = ht,
+ });
+ else
+ drv.outputs.insert_or_assign(i,
+ DerivationOutput::CAFloating {
+ .method = method,
+ .hashType = ht,
+ });
}
}
@@ -1196,44 +1302,34 @@ static void prim_derivationStrict(EvalState & state, const Pos & pos, Value * *
for (auto & i : outputs) {
drv.env[i] = "";
drv.outputs.insert_or_assign(i,
- DerivationOutput {
- .output = DerivationOutputInputAddressed {
- .path = StorePath::dummy,
- },
- });
+ DerivationOutput::Deferred { });
}
- // Regular, non-CA derivation should always return a single hash and not
- // hash per output.
auto hashModulo = hashDerivationModulo(*state.store, Derivation(drv), true);
- std::visit(overloaded {
- [&](Hash & h) {
- for (auto & i : outputs) {
- auto outPath = state.store->makeOutputPath(i, h, drvName);
- drv.env[i] = state.store->printStorePath(outPath);
- drv.outputs.insert_or_assign(i,
- DerivationOutput {
- .output = DerivationOutputInputAddressed {
- .path = std::move(outPath),
- },
- });
- }
- },
- [&](CaOutputHashes &) {
- // Shouldn't happen as the toplevel derivation is not CA.
- assert(false);
- },
- [&](DeferredHash &) {
- for (auto & i : outputs) {
- drv.outputs.insert_or_assign(i,
- DerivationOutput {
- .output = DerivationOutputDeferred{},
- });
- }
- },
- },
- hashModulo);
-
+ switch (hashModulo.kind) {
+ case DrvHash::Kind::Regular:
+ for (auto & i : outputs) {
+ auto h = get(hashModulo.hashes, i);
+ if (!h)
+ throw AssertionError({
+ .msg = hintfmt("derivation produced no hash for output '%s'", i),
+ .errPos = state.positions[posDrvName],
+ });
+ auto outPath = state.store->makeOutputPath(i, *h, drvName);
+ drv.env[i] = state.store->printStorePath(outPath);
+ drv.outputs.insert_or_assign(
+ i,
+ DerivationOutputInputAddressed {
+ .path = std::move(outPath),
+ });
+ }
+ break;
+ ;
+ case DrvHash::Kind::Deferred:
+ for (auto & i : outputs) {
+ drv.outputs.insert_or_assign(i, DerivationOutputDeferred {});
+ }
+ }
}
/* Write the resulting term into the Nix store directory. */
@@ -1244,12 +1340,9 @@ static void prim_derivationStrict(EvalState & state, const Pos & pos, Value * *
/* Optimisation, but required in read-only mode! because in that
case we don't actually write store derivations, so we can't
- read them later.
-
- However, we don't bother doing this for floating CA derivations because
- their "hash modulo" is indeterminate until built. */
- if (drv.type() != DerivationType::CAFloating) {
- auto h = hashDerivationModulo(*state.store, Derivation(drv), false);
+ read them later. */
+ {
+ auto h = hashDerivationModulo(*state.store, drv, false);
drvHashes.lock()->insert_or_assign(drvPath, h);
}
@@ -1273,7 +1366,7 @@ static RegisterPrimOp primop_derivationStrict(RegisterPrimOp::Info {
time, any occurrence of this string in an derivation attribute will
be replaced with the concrete path in the Nix store of the output
‘out’. */
-static void prim_placeholder(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_placeholder(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
v.mkString(hashPlaceholder(state.forceStringNoCtx(*args[0], pos)));
}
@@ -1296,7 +1389,7 @@ static RegisterPrimOp primop_placeholder({
/* Convert the argument to a path. !!! obsolete? */
-static void prim_toPath(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_toPath(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
PathSet context;
Path path = state.coerceToPath(pos, *args[0], context);
@@ -1321,13 +1414,13 @@ static RegisterPrimOp primop_toPath({
/nix/store/newhash-oldhash-oldname. In the past, `toPath' had
special case behaviour for store paths, but that created weird
corner cases. */
-static void prim_storePath(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_storePath(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
if (evalSettings.pureEval)
- throw EvalError({
+ state.debugThrowLastTrace(EvalError({
.msg = hintfmt("'%s' is not allowed in pure evaluation mode", "builtins.storePath"),
- .errPos = pos
- });
+ .errPos = state.positions[pos]
+ }));
PathSet context;
Path path = state.checkSourcePath(state.coerceToPath(pos, *args[0], context));
@@ -1336,10 +1429,10 @@ static void prim_storePath(EvalState & state, const Pos & pos, Value * * args, V
e.g. nix-push does the right thing. */
if (!state.store->isStorePath(path)) path = canonPath(path, true);
if (!state.store->isInStore(path))
- throw EvalError({
+ state.debugThrowLastTrace(EvalError({
.msg = hintfmt("path '%1%' is not in the Nix store", path),
- .errPos = pos
- });
+ .errPos = state.positions[pos]
+ }));
auto path2 = state.store->toStorePath(path).first;
if (!settings.readOnlyMode)
state.store->ensurePath(path2);
@@ -1365,7 +1458,7 @@ static RegisterPrimOp primop_storePath({
.fun = prim_storePath,
});
-static void prim_pathExists(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_pathExists(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
/* We don’t check the path right now, because we don’t want to
throw if the path isn’t allowed, but just return false (and we
@@ -1397,7 +1490,7 @@ static RegisterPrimOp primop_pathExists({
/* Return the base name of the given string, i.e., everything
following the last slash. */
-static void prim_baseNameOf(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_baseNameOf(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
PathSet context;
v.mkString(baseNameOf(*state.coerceToString(pos, *args[0], context, false, false)), context);
@@ -1417,7 +1510,7 @@ static RegisterPrimOp primop_baseNameOf({
/* Return the directory of the given path, i.e., everything before the
last slash. Return either a path or a string depending on the type
of the argument. */
-static void prim_dirOf(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_dirOf(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
PathSet context;
auto path = state.coerceToString(pos, *args[0], context, false, false);
@@ -1437,12 +1530,12 @@ static RegisterPrimOp primop_dirOf({
});
/* Return the contents of a file as a string. */
-static void prim_readFile(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_readFile(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
auto path = realisePath(state, pos, *args[0]);
auto s = readFile(path);
if (s.find((char) 0) != std::string::npos)
- throw Error("the contents of the file '%1%' cannot be represented as a Nix string", path);
+ state.debugThrowLastTrace(Error("the contents of the file '%1%' cannot be represented as a Nix string", path));
StorePathSet refs;
if (state.store->isInStore(path)) {
try {
@@ -1465,7 +1558,7 @@ static RegisterPrimOp primop_readFile({
/* Find a file in the Nix search path. Used to implement <x> paths,
which are desugared to 'findFile __nixPath "x"'. */
-static void prim_findFile(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_findFile(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
state.forceList(*args[0], pos);
@@ -1494,13 +1587,12 @@ static void prim_findFile(EvalState & state, const Pos & pos, Value * * args, Va
auto rewrites = state.realiseContext(context);
path = rewriteStrings(path, rewrites);
} catch (InvalidPathError & e) {
- throw EvalError({
+ state.debugThrowLastTrace(EvalError({
.msg = hintfmt("cannot find '%1%', since path '%2%' is not valid", path, e.path),
- .errPos = pos
- });
+ .errPos = state.positions[pos]
+ }));
}
-
searchPath.emplace_back(prefix, path);
}
@@ -1516,15 +1608,15 @@ static RegisterPrimOp primop_findFile(RegisterPrimOp::Info {
});
/* Return the cryptographic hash of a file in base-16. */
-static void prim_hashFile(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_hashFile(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
auto type = state.forceStringNoCtx(*args[0], pos);
std::optional<HashType> ht = parseHashType(type);
if (!ht)
- throw Error({
+ state.debugThrowLastTrace(Error({
.msg = hintfmt("unknown hash type '%1%'", type),
- .errPos = pos
- });
+ .errPos = state.positions[pos]
+ }));
auto path = realisePath(state, pos, *args[1]);
@@ -1543,7 +1635,7 @@ static RegisterPrimOp primop_hashFile({
});
/* Read a directory (without . or ..) */
-static void prim_readDir(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_readDir(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
auto path = realisePath(state, pos, *args[0]);
@@ -1592,7 +1684,7 @@ static RegisterPrimOp primop_readDir({
/* Convert the argument (which can be any Nix expression) to an XML
representation returned in a string. Not all Nix expressions can
be sensibly or completely represented (e.g., functions). */
-static void prim_toXML(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_toXML(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
std::ostringstream out;
PathSet context;
@@ -1700,7 +1792,7 @@ static RegisterPrimOp primop_toXML({
/* Convert the argument (which can be any Nix expression) to a JSON
string. Not all Nix expressions can be sensibly or completely
represented (e.g., functions). */
-static void prim_toJSON(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_toJSON(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
std::ostringstream out;
PathSet context;
@@ -1723,13 +1815,13 @@ static RegisterPrimOp primop_toJSON({
});
/* Parse a JSON string to a value. */
-static void prim_fromJSON(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_fromJSON(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
auto s = state.forceStringNoCtx(*args[0], pos);
try {
parseJSON(state, s, v);
} catch (JSONParseError &e) {
- e.addTrace(pos, "while decoding a JSON string");
+ e.addTrace(state.positions[pos], "while decoding a JSON string");
throw;
}
}
@@ -1751,7 +1843,7 @@ static RegisterPrimOp primop_fromJSON({
/* Store a string in the Nix store as a source file that can be used
as an input by derivations. */
-static void prim_toFile(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_toFile(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
PathSet context;
std::string name(state.forceStringNoCtx(*args[0], pos));
@@ -1761,25 +1853,26 @@ static void prim_toFile(EvalState & state, const Pos & pos, Value * * args, Valu
for (auto path : context) {
if (path.at(0) != '/')
- throw EvalError( {
+ state.debugThrowLastTrace(EvalError({
.msg = hintfmt(
"in 'toFile': the file named '%1%' must not contain a reference "
"to a derivation but contains (%2%)",
name, path),
- .errPos = pos
- });
+ .errPos = state.positions[pos]
+ }));
refs.insert(state.store->parseStorePath(path));
}
- auto storePath = state.store->printStorePath(settings.readOnlyMode
+ auto storePath = settings.readOnlyMode
? state.store->computeStorePathForText(name, contents, refs)
- : state.store->addTextToStore(name, contents, refs, state.repair));
+ : state.store->addTextToStore(name, contents, refs, state.repair);
/* Note: we don't need to add `context' to the context of the
result, since `storePath' itself has references to the paths
used in args[1]. */
- v.mkString(storePath, {storePath});
+ /* Add the output of this to the allowed paths. */
+ state.allowAndSetStorePathString(storePath, v);
}
static RegisterPrimOp primop_toFile({
@@ -1862,7 +1955,7 @@ static RegisterPrimOp primop_toFile({
static void addPath(
EvalState & state,
- const Pos & pos,
+ const PosIdx pos,
const std::string & name,
Path path,
Value * filterFun,
@@ -1919,40 +2012,35 @@ static void addPath(
if (expectedHash)
expectedStorePath = state.store->makeFixedOutputPath(method, *expectedHash, name);
- Path dstPath;
if (!expectedHash || !state.store->isValidPath(*expectedStorePath)) {
- dstPath = state.store->printStorePath(settings.readOnlyMode
+ StorePath dstPath = settings.readOnlyMode
? state.store->computeStorePathForPath(name, path, method, htSHA256, filter).first
- : state.store->addToStore(name, path, method, htSHA256, filter, state.repair, refs));
- if (expectedHash && expectedStorePath != state.store->parseStorePath(dstPath))
- throw Error("store path mismatch in (possibly filtered) path added from '%s'", path);
+ : state.store->addToStore(name, path, method, htSHA256, filter, state.repair, refs);
+ if (expectedHash && expectedStorePath != dstPath)
+ state.debugThrowLastTrace(Error("store path mismatch in (possibly filtered) path added from '%s'", path));
+ state.allowAndSetStorePathString(dstPath, v);
} else
- dstPath = state.store->printStorePath(*expectedStorePath);
-
- v.mkString(dstPath, {dstPath});
-
- state.allowPath(dstPath);
-
+ state.allowAndSetStorePathString(*expectedStorePath, v);
} catch (Error & e) {
- e.addTrace(pos, "while adding path '%s'", path);
+ e.addTrace(state.positions[pos], "while adding path '%s'", path);
throw;
}
}
-static void prim_filterSource(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_filterSource(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
PathSet context;
Path path = state.coerceToPath(pos, *args[1], context);
state.forceValue(*args[0], pos);
if (args[0]->type() != nFunction)
- throw TypeError({
+ state.debugThrowLastTrace(TypeError({
.msg = hintfmt(
"first argument in call to 'filterSource' is not a function but %1%",
showType(*args[0])),
- .errPos = pos
- });
+ .errPos = state.positions[pos]
+ }));
addPath(state, pos, std::string(baseNameOf(path)), path, args[0], FileIngestionMethod::Recursive, std::nullopt, v, context);
}
@@ -2012,7 +2100,7 @@ static RegisterPrimOp primop_filterSource({
.fun = prim_filterSource,
});
-static void prim_path(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_path(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
state.forceAttrs(*args[0], pos);
Path path;
@@ -2023,29 +2111,29 @@ static void prim_path(EvalState & state, const Pos & pos, Value * * args, Value
PathSet context;
for (auto & attr : *args[0]->attrs) {
- auto & n(attr.name);
+ auto n = state.symbols[attr.name];
if (n == "path")
- path = state.coerceToPath(*attr.pos, *attr.value, context);
+ path = state.coerceToPath(attr.pos, *attr.value, context);
else if (attr.name == state.sName)
- name = state.forceStringNoCtx(*attr.value, *attr.pos);
+ name = state.forceStringNoCtx(*attr.value, attr.pos);
else if (n == "filter") {
state.forceValue(*attr.value, pos);
filterFun = attr.value;
} else if (n == "recursive")
- method = FileIngestionMethod { state.forceBool(*attr.value, *attr.pos) };
+ method = FileIngestionMethod { state.forceBool(*attr.value, attr.pos) };
else if (n == "sha256")
- expectedHash = newHashAllowEmpty(state.forceStringNoCtx(*attr.value, *attr.pos), htSHA256);
+ expectedHash = newHashAllowEmpty(state.forceStringNoCtx(*attr.value, attr.pos), htSHA256);
else
- throw EvalError({
- .msg = hintfmt("unsupported argument '%1%' to 'addPath'", attr.name),
- .errPos = *attr.pos
- });
+ state.debugThrowLastTrace(EvalError({
+ .msg = hintfmt("unsupported argument '%1%' to 'addPath'", state.symbols[attr.name]),
+ .errPos = state.positions[attr.pos]
+ }));
}
if (path.empty())
- throw EvalError({
+ state.debugThrowLastTrace(EvalError({
.msg = hintfmt("'path' required"),
- .errPos = pos
- });
+ .errPos = state.positions[pos]
+ }));
if (name.empty())
name = baseNameOf(path);
@@ -2095,7 +2183,7 @@ static RegisterPrimOp primop_path({
/* Return the names of the attributes in a set as a sorted list of
strings. */
-static void prim_attrNames(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_attrNames(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
state.forceAttrs(*args[0], pos);
@@ -2103,7 +2191,7 @@ static void prim_attrNames(EvalState & state, const Pos & pos, Value * * args, V
size_t n = 0;
for (auto & i : *args[0]->attrs)
- (v.listElems()[n++] = state.allocValue())->mkString(i.name);
+ (v.listElems()[n++] = state.allocValue())->mkString(state.symbols[i.name]);
std::sort(v.listElems(), v.listElems() + n,
[](Value * v1, Value * v2) { return strcmp(v1->string.s, v2->string.s) < 0; });
@@ -2122,7 +2210,7 @@ static RegisterPrimOp primop_attrNames({
/* Return the values of the attributes in a set as a list, in the same
order as attrNames. */
-static void prim_attrValues(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_attrValues(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
state.forceAttrs(*args[0], pos);
@@ -2133,8 +2221,9 @@ static void prim_attrValues(EvalState & state, const Pos & pos, Value * * args,
v.listElems()[n++] = (Value *) &i;
std::sort(v.listElems(), v.listElems() + n,
- [](Value * v1, Value * v2) {
- std::string_view s1 = ((Attr *) v1)->name, s2 = ((Attr *) v2)->name;
+ [&](Value * v1, Value * v2) {
+ std::string_view s1 = state.symbols[((Attr *) v1)->name],
+ s2 = state.symbols[((Attr *) v2)->name];
return s1 < s2;
});
@@ -2153,7 +2242,7 @@ static RegisterPrimOp primop_attrValues({
});
/* Dynamic version of the `.' operator. */
-void prim_getAttr(EvalState & state, const Pos & pos, Value * * args, Value & v)
+void prim_getAttr(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
auto attr = state.forceStringNoCtx(*args[0], pos);
state.forceAttrs(*args[1], pos);
@@ -2165,7 +2254,7 @@ void prim_getAttr(EvalState & state, const Pos & pos, Value * * args, Value & v)
pos
);
// !!! add to stack trace?
- if (state.countCalls && *i->pos != noPos) state.attrSelects[*i->pos]++;
+ if (state.countCalls && i->pos) state.attrSelects[i->pos]++;
state.forceValue(*i->value, pos);
v = *i->value;
}
@@ -2183,7 +2272,7 @@ static RegisterPrimOp primop_getAttr({
});
/* Return position information of the specified attribute. */
-static void prim_unsafeGetAttrPos(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_unsafeGetAttrPos(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
auto attr = state.forceStringNoCtx(*args[0], pos);
state.forceAttrs(*args[1], pos);
@@ -2201,7 +2290,7 @@ static RegisterPrimOp primop_unsafeGetAttrPos(RegisterPrimOp::Info {
});
/* Dynamic version of the `?' operator. */
-static void prim_hasAttr(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_hasAttr(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
auto attr = state.forceStringNoCtx(*args[0], pos);
state.forceAttrs(*args[1], pos);
@@ -2220,7 +2309,7 @@ static RegisterPrimOp primop_hasAttr({
});
/* Determine whether the argument is a set. */
-static void prim_isAttrs(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_isAttrs(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
state.forceValue(*args[0], pos);
v.mkBool(args[0]->type() == nAttrs);
@@ -2235,7 +2324,7 @@ static RegisterPrimOp primop_isAttrs({
.fun = prim_isAttrs,
});
-static void prim_removeAttrs(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_removeAttrs(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
state.forceAttrs(*args[0], pos);
state.forceList(*args[1], pos);
@@ -2283,7 +2372,7 @@ static RegisterPrimOp primop_removeAttrs({
"nameN"; value = valueN;}] is transformed to {name1 = value1;
... nameN = valueN;}. In case of duplicate occurrences of the same
name, the first takes precedence. */
-static void prim_listToAttrs(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_listToAttrs(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
state.forceList(*args[0], pos);
@@ -2302,9 +2391,9 @@ static void prim_listToAttrs(EvalState & state, const Pos & pos, Value * * args,
pos
);
- auto name = state.forceStringNoCtx(*j->value, *j->pos);
+ auto name = state.forceStringNoCtx(*j->value, j->pos);
- Symbol sym = state.symbols.create(name);
+ auto sym = state.symbols.create(name);
if (seen.insert(sym).second) {
Bindings::iterator j2 = getAttr(
state,
@@ -2345,7 +2434,7 @@ static RegisterPrimOp primop_listToAttrs({
.fun = prim_listToAttrs,
});
-static void prim_intersectAttrs(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_intersectAttrs(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
state.forceAttrs(*args[0], pos);
state.forceAttrs(*args[1], pos);
@@ -2365,15 +2454,15 @@ static RegisterPrimOp primop_intersectAttrs({
.name = "__intersectAttrs",
.args = {"e1", "e2"},
.doc = R"(
- Return a set consisting of the attributes in the set *e2* that also
- exist in the set *e1*.
+ Return a set consisting of the attributes in the set *e2* which have the
+ same name as some attribute in *e1*.
)",
.fun = prim_intersectAttrs,
});
-static void prim_catAttrs(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_catAttrs(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
- Symbol attrName = state.symbols.create(state.forceStringNoCtx(*args[0], pos));
+ auto attrName = state.symbols.create(state.forceStringNoCtx(*args[0], pos));
state.forceList(*args[1], pos);
Value * res[args[1]->listSize()];
@@ -2408,7 +2497,7 @@ static RegisterPrimOp primop_catAttrs({
.fun = prim_catAttrs,
});
-static void prim_functionArgs(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_functionArgs(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
state.forceValue(*args[0], pos);
if (args[0]->isPrimOpApp() || args[0]->isPrimOp()) {
@@ -2416,10 +2505,10 @@ static void prim_functionArgs(EvalState & state, const Pos & pos, Value * * args
return;
}
if (!args[0]->isLambda())
- throw TypeError({
+ state.debugThrowLastTrace(TypeError({
.msg = hintfmt("'functionArgs' requires a function"),
- .errPos = pos
- });
+ .errPos = state.positions[pos]
+ }));
if (!args[0]->lambda.fun->hasFormals()) {
v.mkAttrs(&state.emptyBindings);
@@ -2429,7 +2518,7 @@ static void prim_functionArgs(EvalState & state, const Pos & pos, Value * * args
auto attrs = state.buildBindings(args[0]->lambda.fun->formals->formals.size());
for (auto & i : args[0]->lambda.fun->formals->formals)
// !!! should optimise booleans (allocate only once)
- attrs.alloc(i.name, ptr(&i.pos)).mkBool(i.def);
+ attrs.alloc(i.name, i.pos).mkBool(i.def);
v.mkAttrs(attrs);
}
@@ -2451,7 +2540,7 @@ static RegisterPrimOp primop_functionArgs({
});
/* */
-static void prim_mapAttrs(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_mapAttrs(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
state.forceAttrs(*args[1], pos);
@@ -2460,7 +2549,7 @@ static void prim_mapAttrs(EvalState & state, const Pos & pos, Value * * args, Va
for (auto & i : *args[1]->attrs) {
Value * vName = state.allocValue();
Value * vFun2 = state.allocValue();
- vName->mkString(i.name);
+ vName->mkString(state.symbols[i.name]);
vFun2->mkApp(args[0], vName);
attrs.alloc(i.name).mkApp(vFun2, i.value);
}
@@ -2483,7 +2572,7 @@ static RegisterPrimOp primop_mapAttrs({
.fun = prim_mapAttrs,
});
-static void prim_zipAttrsWith(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_zipAttrsWith(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
// we will first count how many values are present for each given key.
// we then allocate a single attrset and pre-populate it with lists of
@@ -2506,8 +2595,8 @@ static void prim_zipAttrsWith(EvalState & state, const Pos & pos, Value * * args
for (auto & attr : *vElem->attrs)
attrsSeen[attr.name].first++;
} catch (TypeError & e) {
- e.addTrace(pos, hintfmt("while invoking '%s'", "zipAttrsWith"));
- throw;
+ e.addTrace(state.positions[pos], hintfmt("while invoking '%s'", "zipAttrsWith"));
+ state.debugThrowLastTrace(e);
}
}
@@ -2527,7 +2616,7 @@ static void prim_zipAttrsWith(EvalState & state, const Pos & pos, Value * * args
for (auto & attr : *v.attrs) {
auto name = state.allocValue();
- name->mkString(attr.name);
+ name->mkString(state.symbols[attr.name]);
auto call1 = state.allocValue();
call1->mkApp(args[0], name);
auto call2 = state.allocValue();
@@ -2575,7 +2664,7 @@ static RegisterPrimOp primop_zipAttrsWith({
/* Determine whether the argument is a list. */
-static void prim_isList(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_isList(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
state.forceValue(*args[0], pos);
v.mkBool(args[0]->type() == nList);
@@ -2590,20 +2679,20 @@ static RegisterPrimOp primop_isList({
.fun = prim_isList,
});
-static void elemAt(EvalState & state, const Pos & pos, Value & list, int n, Value & v)
+static void elemAt(EvalState & state, const PosIdx pos, Value & list, int n, Value & v)
{
state.forceList(list, pos);
if (n < 0 || (unsigned int) n >= list.listSize())
- throw Error({
+ state.debugThrowLastTrace(Error({
.msg = hintfmt("list index %1% is out of bounds", n),
- .errPos = pos
- });
+ .errPos = state.positions[pos]
+ }));
state.forceValue(*list.listElems()[n], pos);
v = *list.listElems()[n];
}
/* Return the n-1'th element of a list. */
-static void prim_elemAt(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_elemAt(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
elemAt(state, pos, *args[0], state.forceInt(*args[1], pos), v);
}
@@ -2619,7 +2708,7 @@ static RegisterPrimOp primop_elemAt({
});
/* Return the first element of a list. */
-static void prim_head(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_head(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
elemAt(state, pos, *args[0], 0, v);
}
@@ -2638,14 +2727,14 @@ static RegisterPrimOp primop_head({
/* Return a list consisting of everything but the first element of
a list. Warning: this function takes O(n) time, so you probably
don't want to use it! */
-static void prim_tail(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_tail(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
state.forceList(*args[0], pos);
if (args[0]->listSize() == 0)
- throw Error({
+ state.debugThrowLastTrace(Error({
.msg = hintfmt("'tail' called on an empty list"),
- .errPos = pos
- });
+ .errPos = state.positions[pos]
+ }));
state.mkList(v, args[0]->listSize() - 1);
for (unsigned int n = 0; n < v.listSize(); ++n)
@@ -2669,7 +2758,7 @@ static RegisterPrimOp primop_tail({
});
/* Apply a function to every element of a list. */
-static void prim_map(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_map(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
state.forceList(*args[1], pos);
@@ -2699,7 +2788,7 @@ static RegisterPrimOp primop_map({
/* Filter a list using a predicate; that is, return a list containing
every element from the list for which the predicate function
returns true. */
-static void prim_filter(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_filter(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
state.forceFunction(*args[0], pos);
state.forceList(*args[1], pos);
@@ -2737,7 +2826,7 @@ static RegisterPrimOp primop_filter({
});
/* Return true if a list contains a given element. */
-static void prim_elem(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_elem(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
bool res = false;
state.forceList(*args[1], pos);
@@ -2760,7 +2849,7 @@ static RegisterPrimOp primop_elem({
});
/* Concatenate a list of lists. */
-static void prim_concatLists(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_concatLists(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
state.forceList(*args[0], pos);
state.concatLists(v, args[0]->listSize(), args[0]->listElems(), pos);
@@ -2776,7 +2865,7 @@ static RegisterPrimOp primop_concatLists({
});
/* Return the length of a list. This is an O(1) time operation. */
-static void prim_length(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_length(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
state.forceList(*args[0], pos);
v.mkInt(args[0]->listSize());
@@ -2793,7 +2882,7 @@ static RegisterPrimOp primop_length({
/* Reduce a list by applying a binary operator, from left to
right. The operator is applied strictly. */
-static void prim_foldlStrict(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_foldlStrict(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
state.forceFunction(*args[0], pos);
state.forceList(*args[2], pos);
@@ -2826,7 +2915,7 @@ static RegisterPrimOp primop_foldlStrict({
.fun = prim_foldlStrict,
});
-static void anyOrAll(bool any, EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void anyOrAll(bool any, EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
state.forceFunction(*args[0], pos);
state.forceList(*args[1], pos);
@@ -2845,7 +2934,7 @@ static void anyOrAll(bool any, EvalState & state, const Pos & pos, Value * * arg
}
-static void prim_any(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_any(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
anyOrAll(true, state, pos, args, v);
}
@@ -2860,7 +2949,7 @@ static RegisterPrimOp primop_any({
.fun = prim_any,
});
-static void prim_all(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_all(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
anyOrAll(false, state, pos, args, v);
}
@@ -2875,15 +2964,15 @@ static RegisterPrimOp primop_all({
.fun = prim_all,
});
-static void prim_genList(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_genList(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
auto len = state.forceInt(*args[1], pos);
if (len < 0)
- throw EvalError({
+ state.debugThrowLastTrace(EvalError({
.msg = hintfmt("cannot create list of size %1%", len),
- .errPos = pos
- });
+ .errPos = state.positions[pos]
+ }));
state.mkList(v, len);
@@ -2910,10 +2999,10 @@ static RegisterPrimOp primop_genList({
.fun = prim_genList,
});
-static void prim_lessThan(EvalState & state, const Pos & pos, Value * * args, Value & v);
+static void prim_lessThan(EvalState & state, const PosIdx pos, Value * * args, Value & v);
-static void prim_sort(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_sort(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
state.forceFunction(*args[0], pos);
state.forceList(*args[1], pos);
@@ -2964,7 +3053,7 @@ static RegisterPrimOp primop_sort({
.fun = prim_sort,
});
-static void prim_partition(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_partition(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
state.forceFunction(*args[0], pos);
state.forceList(*args[1], pos);
@@ -3024,7 +3113,7 @@ static RegisterPrimOp primop_partition({
.fun = prim_partition,
});
-static void prim_groupBy(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_groupBy(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
state.forceFunction(*args[0], pos);
state.forceList(*args[1], pos);
@@ -3035,7 +3124,7 @@ static void prim_groupBy(EvalState & state, const Pos & pos, Value * * args, Val
Value res;
state.callFunction(*args[0], *vElem, res, pos);
auto name = state.forceStringNoCtx(res, pos);
- Symbol sym = state.symbols.create(name);
+ auto sym = state.symbols.create(name);
auto vector = attrs.try_emplace(sym, ValueVector()).first;
vector->second.push_back(vElem);
}
@@ -3076,7 +3165,7 @@ static RegisterPrimOp primop_groupBy({
.fun = prim_groupBy,
});
-static void prim_concatMap(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_concatMap(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
state.forceFunction(*args[0], pos);
state.forceList(*args[1], pos);
@@ -3091,8 +3180,8 @@ static void prim_concatMap(EvalState & state, const Pos & pos, Value * * args, V
try {
state.forceList(lists[n], lists[n].determinePos(args[0]->determinePos(pos)));
} catch (TypeError &e) {
- e.addTrace(pos, hintfmt("while invoking '%s'", "concatMap"));
- throw;
+ e.addTrace(state.positions[pos], hintfmt("while invoking '%s'", "concatMap"));
+ state.debugThrowLastTrace(e);
}
len += lists[n].listSize();
}
@@ -3123,7 +3212,7 @@ static RegisterPrimOp primop_concatMap({
*************************************************************/
-static void prim_add(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_add(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
state.forceValue(*args[0], pos);
state.forceValue(*args[1], pos);
@@ -3142,7 +3231,7 @@ static RegisterPrimOp primop_add({
.fun = prim_add,
});
-static void prim_sub(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_sub(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
state.forceValue(*args[0], pos);
state.forceValue(*args[1], pos);
@@ -3161,7 +3250,7 @@ static RegisterPrimOp primop_sub({
.fun = prim_sub,
});
-static void prim_mul(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_mul(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
state.forceValue(*args[0], pos);
state.forceValue(*args[1], pos);
@@ -3180,17 +3269,17 @@ static RegisterPrimOp primop_mul({
.fun = prim_mul,
});
-static void prim_div(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_div(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
state.forceValue(*args[0], pos);
state.forceValue(*args[1], pos);
NixFloat f2 = state.forceFloat(*args[1], pos);
if (f2 == 0)
- throw EvalError({
+ state.debugThrowLastTrace(EvalError({
.msg = hintfmt("division by zero"),
- .errPos = pos
- });
+ .errPos = state.positions[pos]
+ }));
if (args[0]->type() == nFloat || args[1]->type() == nFloat) {
v.mkFloat(state.forceFloat(*args[0], pos) / state.forceFloat(*args[1], pos));
@@ -3199,10 +3288,10 @@ static void prim_div(EvalState & state, const Pos & pos, Value * * args, Value &
NixInt i2 = state.forceInt(*args[1], pos);
/* Avoid division overflow as it might raise SIGFPE. */
if (i1 == std::numeric_limits<NixInt>::min() && i2 == -1)
- throw EvalError({
+ state.debugThrowLastTrace(EvalError({
.msg = hintfmt("overflow in integer division"),
- .errPos = pos
- });
+ .errPos = state.positions[pos]
+ }));
v.mkInt(i1 / i2);
}
@@ -3217,7 +3306,7 @@ static RegisterPrimOp primop_div({
.fun = prim_div,
});
-static void prim_bitAnd(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_bitAnd(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
v.mkInt(state.forceInt(*args[0], pos) & state.forceInt(*args[1], pos));
}
@@ -3231,7 +3320,7 @@ static RegisterPrimOp primop_bitAnd({
.fun = prim_bitAnd,
});
-static void prim_bitOr(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_bitOr(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
v.mkInt(state.forceInt(*args[0], pos) | state.forceInt(*args[1], pos));
}
@@ -3245,7 +3334,7 @@ static RegisterPrimOp primop_bitOr({
.fun = prim_bitOr,
});
-static void prim_bitXor(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_bitXor(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
v.mkInt(state.forceInt(*args[0], pos) ^ state.forceInt(*args[1], pos));
}
@@ -3259,7 +3348,7 @@ static RegisterPrimOp primop_bitXor({
.fun = prim_bitXor,
});
-static void prim_lessThan(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_lessThan(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
state.forceValue(*args[0], pos);
state.forceValue(*args[1], pos);
@@ -3287,7 +3376,7 @@ static RegisterPrimOp primop_lessThan({
/* Convert the argument to a string. Paths are *not* copied to the
store, so `toString /foo/bar' yields `"/foo/bar"', not
`"/nix/store/whatever..."'. */
-static void prim_toString(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_toString(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
PathSet context;
auto s = state.coerceToString(pos, *args[0], context, true, false);
@@ -3322,7 +3411,7 @@ static RegisterPrimOp primop_toString({
at character position `min(start, stringLength str)' inclusive and
ending at `min(start + len, stringLength str)'. `start' must be
non-negative. */
-static void prim_substring(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_substring(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
int start = state.forceInt(*args[0], pos);
int len = state.forceInt(*args[1], pos);
@@ -3330,10 +3419,10 @@ static void prim_substring(EvalState & state, const Pos & pos, Value * * args, V
auto s = state.coerceToString(pos, *args[2], context);
if (start < 0)
- throw EvalError({
+ state.debugThrowLastTrace(EvalError({
.msg = hintfmt("negative start position in 'substring'"),
- .errPos = pos
- });
+ .errPos = state.positions[pos]
+ }));
v.mkString((unsigned int) start >= s->size() ? "" : s->substr(start, len), context);
}
@@ -3358,7 +3447,7 @@ static RegisterPrimOp primop_substring({
.fun = prim_substring,
});
-static void prim_stringLength(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_stringLength(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
PathSet context;
auto s = state.coerceToString(pos, *args[0], context);
@@ -3376,15 +3465,15 @@ static RegisterPrimOp primop_stringLength({
});
/* Return the cryptographic hash of a string in base-16. */
-static void prim_hashString(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_hashString(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
auto type = state.forceStringNoCtx(*args[0], pos);
std::optional<HashType> ht = parseHashType(type);
if (!ht)
- throw Error({
+ state.debugThrowLastTrace(Error({
.msg = hintfmt("unknown hash type '%1%'", type),
- .errPos = pos
- });
+ .errPos = state.positions[pos]
+ }));
PathSet context; // discarded
auto s = state.forceString(*args[1], context, pos);
@@ -3424,7 +3513,7 @@ std::shared_ptr<RegexCache> makeRegexCache()
return std::make_shared<RegexCache>();
}
-void prim_match(EvalState & state, const Pos & pos, Value * * args, Value & v)
+void prim_match(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
auto re = state.forceStringNoCtx(*args[0], pos);
@@ -3451,19 +3540,18 @@ void prim_match(EvalState & state, const Pos & pos, Value * * args, Value & v)
(v.listElems()[i] = state.allocValue())->mkString(match[i + 1].str());
}
- } catch (std::regex_error &e) {
+ } catch (std::regex_error & e) {
if (e.code() == std::regex_constants::error_space) {
// limit is _GLIBCXX_REGEX_STATE_LIMIT for libstdc++
- throw EvalError({
+ state.debugThrowLastTrace(EvalError({
.msg = hintfmt("memory limit exceeded by regular expression '%s'", re),
- .errPos = pos
- });
- } else {
- throw EvalError({
+ .errPos = state.positions[pos]
+ }));
+ } else
+ state.debugThrowLastTrace(EvalError({
.msg = hintfmt("invalid regular expression '%s'", re),
- .errPos = pos
- });
- }
+ .errPos = state.positions[pos]
+ }));
}
}
@@ -3498,14 +3586,14 @@ static RegisterPrimOp primop_match({
builtins.match "[[:space:]]+([[:upper:]]+)[[:space:]]+" " FOO "
```
- Evaluates to `[ "foo" ]`.
+ Evaluates to `[ "FOO" ]`.
)s",
.fun = prim_match,
});
/* Split a string with a regular expression, and return a list of the
non-matching parts interleaved by the lists of the matching groups. */
-void prim_split(EvalState & state, const Pos & pos, Value * * args, Value & v)
+void prim_split(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
auto re = state.forceStringNoCtx(*args[0], pos);
@@ -3556,19 +3644,18 @@ void prim_split(EvalState & state, const Pos & pos, Value * * args, Value & v)
assert(idx == 2 * len + 1);
- } catch (std::regex_error &e) {
+ } catch (std::regex_error & e) {
if (e.code() == std::regex_constants::error_space) {
// limit is _GLIBCXX_REGEX_STATE_LIMIT for libstdc++
- throw EvalError({
+ state.debugThrowLastTrace(EvalError({
.msg = hintfmt("memory limit exceeded by regular expression '%s'", re),
- .errPos = pos
- });
- } else {
- throw EvalError({
+ .errPos = state.positions[pos]
+ }));
+ } else
+ state.debugThrowLastTrace(EvalError({
.msg = hintfmt("invalid regular expression '%s'", re),
- .errPos = pos
- });
- }
+ .errPos = state.positions[pos]
+ }));
}
}
@@ -3601,7 +3688,7 @@ static RegisterPrimOp primop_split({
Evaluates to `[ "" [ "a" null ] "b" [ null "c" ] "" ]`.
```nix
- builtins.split "([[:upper:]]+)" " FOO "
+ builtins.split "([[:upper:]]+)" " FOO "
```
Evaluates to `[ " " [ "FOO" ] " " ]`.
@@ -3609,7 +3696,7 @@ static RegisterPrimOp primop_split({
.fun = prim_split,
});
-static void prim_concatStringsSep(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_concatStringsSep(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
PathSet context;
@@ -3639,15 +3726,15 @@ static RegisterPrimOp primop_concatStringsSep({
.fun = prim_concatStringsSep,
});
-static void prim_replaceStrings(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_replaceStrings(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
state.forceList(*args[0], pos);
state.forceList(*args[1], pos);
if (args[0]->listSize() != args[1]->listSize())
- throw EvalError({
+ state.debugThrowLastTrace(EvalError({
.msg = hintfmt("'from' and 'to' arguments to 'replaceStrings' have different lengths"),
- .errPos = pos
- });
+ .errPos = state.positions[pos]
+ }));
std::vector<std::string> from;
from.reserve(args[0]->listSize());
@@ -3719,7 +3806,7 @@ static RegisterPrimOp primop_replaceStrings({
*************************************************************/
-static void prim_parseDrvName(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_parseDrvName(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
auto name = state.forceStringNoCtx(*args[0], pos);
DrvName parsed(name);
@@ -3734,8 +3821,8 @@ static RegisterPrimOp primop_parseDrvName({
.args = {"s"},
.doc = R"(
Split the string *s* into a package name and version. The package
- name is everything up to but not including the first dash followed
- by a digit, and the version is everything following that dash. The
+ name is everything up to but not including the first dash not followed
+ by a letter, and the version is everything following that dash. The
result is returned in a set `{ name, version }`. Thus,
`builtins.parseDrvName "nix-0.12pre12876"` returns `{ name =
"nix"; version = "0.12pre12876"; }`.
@@ -3743,7 +3830,7 @@ static RegisterPrimOp primop_parseDrvName({
.fun = prim_parseDrvName,
});
-static void prim_compareVersions(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_compareVersions(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
auto version1 = state.forceStringNoCtx(*args[0], pos);
auto version2 = state.forceStringNoCtx(*args[1], pos);
@@ -3763,7 +3850,7 @@ static RegisterPrimOp primop_compareVersions({
.fun = prim_compareVersions,
});
-static void prim_splitVersion(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_splitVersion(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
auto version = state.forceStringNoCtx(*args[0], pos);
auto iter = version.cbegin();
@@ -3806,7 +3893,7 @@ RegisterPrimOp::RegisterPrimOp(std::string name, size_t arity, PrimOpFun fun)
.name = name,
.args = {},
.arity = arity,
- .fun = fun
+ .fun = fun,
});
}
@@ -3865,6 +3952,18 @@ void EvalState::createBaseEnv()
addPrimOp("__exec", 1, prim_exec);
}
+ addPrimOp({
+ .fun = evalSettings.traceVerbose ? prim_trace : prim_second,
+ .arity = 2,
+ .name = "__traceVerbose",
+ .args = { "e1", "e2" },
+ .doc = R"(
+ Evaluate *e1* and print its abstract syntax representation on standard
+ error if `--trace-verbose` is enabled. Then return *e2*. This function
+ is useful for debugging.
+ )",
+ });
+
/* Add a value containing the current Nix expression search path. */
mkList(v, searchPath.size());
int n = 0;
@@ -3878,17 +3977,21 @@ void EvalState::createBaseEnv()
if (RegisterPrimOp::primOps)
for (auto & primOp : *RegisterPrimOp::primOps)
- addPrimOp({
- .fun = primOp.fun,
- .arity = std::max(primOp.args.size(), primOp.arity),
- .name = symbols.create(primOp.name),
- .args = primOp.args,
- .doc = primOp.doc,
- });
+ if (!primOp.experimentalFeature
+ || settings.isExperimentalFeatureEnabled(*primOp.experimentalFeature))
+ {
+ addPrimOp({
+ .fun = primOp.fun,
+ .arity = std::max(primOp.args.size(), primOp.arity),
+ .name = primOp.name,
+ .args = primOp.args,
+ .doc = primOp.doc,
+ });
+ }
/* Add a wrapper around the derivation primop that computes the
`drvPath' and `outPath' attributes lazily. */
- sDerivationNix = symbols.create("//builtin/derivation.nix");
+ sDerivationNix = symbols.create(derivationNixPath);
auto vDerivation = allocValue();
addConstant("derivation", vDerivation);
@@ -3896,7 +3999,7 @@ void EvalState::createBaseEnv()
because attribute lookups expect it to be sorted. */
baseEnv.values[0]->attrs->sort();
- staticBaseEnv.sort();
+ staticBaseEnv->sort();
/* Note: we have to initialize the 'derivation' constant *after*
building baseEnv/staticBaseEnv because it uses 'builtins'. */
@@ -3905,7 +4008,7 @@ void EvalState::createBaseEnv()
// the parser needs two NUL bytes as terminators; one of them
// is implied by being a C string.
"\0";
- eval(parse(code, sizeof(code), foFile, sDerivationNix, "/", staticBaseEnv), *vDerivation);
+ eval(parse(code, sizeof(code), foFile, derivationNixPath, "/", staticBaseEnv), *vDerivation);
}
diff --git a/src/libexpr/primops.hh b/src/libexpr/primops.hh
index 5b16e075f..1cfb4356b 100644
--- a/src/libexpr/primops.hh
+++ b/src/libexpr/primops.hh
@@ -16,6 +16,7 @@ struct RegisterPrimOp
size_t arity = 0;
const char * doc;
PrimOpFun fun;
+ std::optional<ExperimentalFeature> experimentalFeature;
};
typedef std::vector<Info> PrimOps;
@@ -35,10 +36,11 @@ struct RegisterPrimOp
/* These primops are disabled without enableNativeCode, but plugins
may wish to use them in limited contexts without globally enabling
them. */
+
/* Load a ValueInitializer from a DSO and return whatever it initializes */
-void prim_importNative(EvalState & state, const Pos & pos, Value * * args, Value & v);
+void prim_importNative(EvalState & state, const PosIdx pos, Value * * args, Value & v);
/* Execute a program and parse its output */
-void prim_exec(EvalState & state, const Pos & pos, Value * * args, Value & v);
+void prim_exec(EvalState & state, const PosIdx pos, Value * * args, Value & v);
}
diff --git a/src/libexpr/primops/context.cc b/src/libexpr/primops/context.cc
index 3701bd442..979136984 100644
--- a/src/libexpr/primops/context.cc
+++ b/src/libexpr/primops/context.cc
@@ -1,10 +1,11 @@
#include "primops.hh"
#include "eval-inline.hh"
+#include "derivations.hh"
#include "store-api.hh"
namespace nix {
-static void prim_unsafeDiscardStringContext(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_unsafeDiscardStringContext(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
PathSet context;
auto s = state.coerceToString(pos, *args[0], context);
@@ -14,7 +15,7 @@ static void prim_unsafeDiscardStringContext(EvalState & state, const Pos & pos,
static RegisterPrimOp primop_unsafeDiscardStringContext("__unsafeDiscardStringContext", 1, prim_unsafeDiscardStringContext);
-static void prim_hasContext(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_hasContext(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
PathSet context;
state.forceString(*args[0], context, pos);
@@ -30,7 +31,7 @@ static RegisterPrimOp primop_hasContext("__hasContext", 1, prim_hasContext);
source-only deployment). This primop marks the string context so
that builtins.derivation adds the path to drv.inputSrcs rather than
drv.inputDrvs. */
-static void prim_unsafeDiscardOutputDependency(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_unsafeDiscardOutputDependency(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
PathSet context;
auto s = state.coerceToString(pos, *args[0], context);
@@ -64,7 +65,7 @@ static RegisterPrimOp primop_unsafeDiscardOutputDependency("__unsafeDiscardOutpu
Note that for a given path any combination of the above attributes
may be present.
*/
-static void prim_getContext(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_getContext(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
struct ContextInfo {
bool path = false;
@@ -82,8 +83,8 @@ static void prim_getContext(EvalState & state, const Pos & pos, Value * * args,
drv = std::string(p, 1);
path = &drv;
} else if (p.at(0) == '!') {
- std::pair<std::string, std::string> ctx = decodeContext(p);
- drv = ctx.first;
+ NixStringContextElem ctx = decodeContext(*state.store, p);
+ drv = state.store->printStorePath(ctx.first);
output = ctx.second;
path = &drv;
}
@@ -133,7 +134,7 @@ static RegisterPrimOp primop_getContext("__getContext", 1, prim_getContext);
See the commentary above unsafeGetContext for details of the
context representation.
*/
-static void prim_appendContext(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_appendContext(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
PathSet context;
auto orig = state.forceString(*args[0], context, pos);
@@ -143,45 +144,46 @@ static void prim_appendContext(EvalState & state, const Pos & pos, Value * * arg
auto sPath = state.symbols.create("path");
auto sAllOutputs = state.symbols.create("allOutputs");
for (auto & i : *args[1]->attrs) {
- if (!state.store->isStorePath(i.name))
+ const auto & name = state.symbols[i.name];
+ if (!state.store->isStorePath(name))
throw EvalError({
- .msg = hintfmt("Context key '%s' is not a store path", i.name),
- .errPos = *i.pos
+ .msg = hintfmt("Context key '%s' is not a store path", name),
+ .errPos = state.positions[i.pos]
});
if (!settings.readOnlyMode)
- state.store->ensurePath(state.store->parseStorePath(i.name));
- state.forceAttrs(*i.value, *i.pos);
+ state.store->ensurePath(state.store->parseStorePath(name));
+ state.forceAttrs(*i.value, i.pos);
auto iter = i.value->attrs->find(sPath);
if (iter != i.value->attrs->end()) {
- if (state.forceBool(*iter->value, *iter->pos))
- context.insert(i.name);
+ if (state.forceBool(*iter->value, iter->pos))
+ context.emplace(name);
}
iter = i.value->attrs->find(sAllOutputs);
if (iter != i.value->attrs->end()) {
- if (state.forceBool(*iter->value, *iter->pos)) {
- if (!isDerivation(i.name)) {
+ if (state.forceBool(*iter->value, iter->pos)) {
+ if (!isDerivation(name)) {
throw EvalError({
- .msg = hintfmt("Tried to add all-outputs context of %s, which is not a derivation, to a string", i.name),
- .errPos = *i.pos
+ .msg = hintfmt("Tried to add all-outputs context of %s, which is not a derivation, to a string", name),
+ .errPos = state.positions[i.pos]
});
}
- context.insert("=" + std::string(i.name));
+ context.insert(concatStrings("=", name));
}
}
iter = i.value->attrs->find(state.sOutputs);
if (iter != i.value->attrs->end()) {
- state.forceList(*iter->value, *iter->pos);
- if (iter->value->listSize() && !isDerivation(i.name)) {
+ state.forceList(*iter->value, iter->pos);
+ if (iter->value->listSize() && !isDerivation(name)) {
throw EvalError({
- .msg = hintfmt("Tried to add derivation output context of %s, which is not a derivation, to a string", i.name),
- .errPos = *i.pos
+ .msg = hintfmt("Tried to add derivation output context of %s, which is not a derivation, to a string", name),
+ .errPos = state.positions[i.pos]
});
}
for (auto elem : iter->value->listItems()) {
- auto name = state.forceStringNoCtx(*elem, *iter->pos);
- context.insert(concatStrings("!", name, "!", i.name));
+ auto outputName = state.forceStringNoCtx(*elem, iter->pos);
+ context.insert(concatStrings("!", outputName, "!", name));
}
}
}
diff --git a/src/libexpr/primops/fetchClosure.cc b/src/libexpr/primops/fetchClosure.cc
new file mode 100644
index 000000000..662c9652e
--- /dev/null
+++ b/src/libexpr/primops/fetchClosure.cc
@@ -0,0 +1,163 @@
+#include "primops.hh"
+#include "store-api.hh"
+#include "make-content-addressed.hh"
+#include "url.hh"
+
+namespace nix {
+
+static void prim_fetchClosure(EvalState & state, const PosIdx pos, Value * * args, Value & v)
+{
+ state.forceAttrs(*args[0], pos);
+
+ std::optional<std::string> fromStoreUrl;
+ std::optional<StorePath> fromPath;
+ bool toCA = false;
+ std::optional<StorePath> toPath;
+
+ for (auto & attr : *args[0]->attrs) {
+ const auto & attrName = state.symbols[attr.name];
+
+ if (attrName == "fromPath") {
+ PathSet context;
+ fromPath = state.coerceToStorePath(attr.pos, *attr.value, context);
+ }
+
+ else if (attrName == "toPath") {
+ state.forceValue(*attr.value, attr.pos);
+ toCA = true;
+ if (attr.value->type() != nString || attr.value->string.s != std::string("")) {
+ PathSet context;
+ toPath = state.coerceToStorePath(attr.pos, *attr.value, context);
+ }
+ }
+
+ else if (attrName == "fromStore")
+ fromStoreUrl = state.forceStringNoCtx(*attr.value, attr.pos);
+
+ else
+ throw Error({
+ .msg = hintfmt("attribute '%s' isn't supported in call to 'fetchClosure'", attrName),
+ .errPos = state.positions[pos]
+ });
+ }
+
+ if (!fromPath)
+ throw Error({
+ .msg = hintfmt("attribute '%s' is missing in call to 'fetchClosure'", "fromPath"),
+ .errPos = state.positions[pos]
+ });
+
+ if (!fromStoreUrl)
+ throw Error({
+ .msg = hintfmt("attribute '%s' is missing in call to 'fetchClosure'", "fromStore"),
+ .errPos = state.positions[pos]
+ });
+
+ auto parsedURL = parseURL(*fromStoreUrl);
+
+ if (parsedURL.scheme != "http" &&
+ parsedURL.scheme != "https" &&
+ !(getEnv("_NIX_IN_TEST").has_value() && parsedURL.scheme == "file"))
+ throw Error({
+ .msg = hintfmt("'fetchClosure' only supports http:// and https:// stores"),
+ .errPos = state.positions[pos]
+ });
+
+ if (!parsedURL.query.empty())
+ throw Error({
+ .msg = hintfmt("'fetchClosure' does not support URL query parameters (in '%s')", *fromStoreUrl),
+ .errPos = state.positions[pos]
+ });
+
+ auto fromStore = openStore(parsedURL.to_string());
+
+ if (toCA) {
+ if (!toPath || !state.store->isValidPath(*toPath)) {
+ auto remappings = makeContentAddressed(*fromStore, *state.store, { *fromPath });
+ auto i = remappings.find(*fromPath);
+ assert(i != remappings.end());
+ if (toPath && *toPath != i->second)
+ throw Error({
+ .msg = hintfmt("rewriting '%s' to content-addressed form yielded '%s', while '%s' was expected",
+ state.store->printStorePath(*fromPath),
+ state.store->printStorePath(i->second),
+ state.store->printStorePath(*toPath)),
+ .errPos = state.positions[pos]
+ });
+ if (!toPath)
+ throw Error({
+ .msg = hintfmt(
+ "rewriting '%s' to content-addressed form yielded '%s'; "
+ "please set this in the 'toPath' attribute passed to 'fetchClosure'",
+ state.store->printStorePath(*fromPath),
+ state.store->printStorePath(i->second)),
+ .errPos = state.positions[pos]
+ });
+ }
+ } else {
+ if (!state.store->isValidPath(*fromPath))
+ copyClosure(*fromStore, *state.store, RealisedPath::Set { *fromPath });
+ toPath = fromPath;
+ }
+
+ /* In pure mode, require a CA path. */
+ if (evalSettings.pureEval) {
+ auto info = state.store->queryPathInfo(*toPath);
+ if (!info->isContentAddressed(*state.store))
+ throw Error({
+ .msg = hintfmt("in pure mode, 'fetchClosure' requires a content-addressed path, which '%s' isn't",
+ state.store->printStorePath(*toPath)),
+ .errPos = state.positions[pos]
+ });
+ }
+
+ auto toPathS = state.store->printStorePath(*toPath);
+ v.mkString(toPathS, {toPathS});
+}
+
+static RegisterPrimOp primop_fetchClosure({
+ .name = "__fetchClosure",
+ .args = {"args"},
+ .doc = R"(
+ Fetch a Nix store closure from a binary cache, rewriting it into
+ content-addressed form. For example,
+
+ ```nix
+ builtins.fetchClosure {
+ fromStore = "https://cache.nixos.org";
+ fromPath = /nix/store/r2jd6ygnmirm2g803mksqqjm4y39yi6i-git-2.33.1;
+ toPath = /nix/store/ldbhlwhh39wha58rm61bkiiwm6j7211j-git-2.33.1;
+ }
+ ```
+
+ fetches `/nix/store/r2jd...` from the specified binary cache,
+ and rewrites it into the content-addressed store path
+ `/nix/store/ldbh...`.
+
+ If `fromPath` is already content-addressed, or if you are
+ allowing impure evaluation (`--impure`), then `toPath` may be
+ omitted.
+
+ To find out the correct value for `toPath` given a `fromPath`,
+ you can use `nix store make-content-addressed`:
+
+ ```console
+ # nix store make-content-addressed --from https://cache.nixos.org /nix/store/r2jd6ygnmirm2g803mksqqjm4y39yi6i-git-2.33.1
+ rewrote '/nix/store/r2jd6ygnmirm2g803mksqqjm4y39yi6i-git-2.33.1' to '/nix/store/ldbhlwhh39wha58rm61bkiiwm6j7211j-git-2.33.1'
+ ```
+
+ This function is similar to `builtins.storePath` in that it
+ allows you to use a previously built store path in a Nix
+ expression. However, it is more reproducible because it requires
+ specifying a binary cache from which the path can be fetched.
+ Also, requiring a content-addressed final store path avoids the
+ need for users to configure binary cache public keys.
+
+ This function is only available if you enable the experimental
+ feature `fetch-closure`.
+ )",
+ .fun = prim_fetchClosure,
+ .experimentalFeature = Xp::FetchClosure,
+});
+
+}
diff --git a/src/libexpr/primops/fetchMercurial.cc b/src/libexpr/primops/fetchMercurial.cc
index b7f715859..249c0934e 100644
--- a/src/libexpr/primops/fetchMercurial.cc
+++ b/src/libexpr/primops/fetchMercurial.cc
@@ -7,7 +7,7 @@
namespace nix {
-static void prim_fetchMercurial(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_fetchMercurial(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
std::string url;
std::optional<Hash> rev;
@@ -22,31 +22,31 @@ static void prim_fetchMercurial(EvalState & state, const Pos & pos, Value * * ar
state.forceAttrs(*args[0], pos);
for (auto & attr : *args[0]->attrs) {
- std::string_view n(attr.name);
+ std::string_view n(state.symbols[attr.name]);
if (n == "url")
- url = state.coerceToString(*attr.pos, *attr.value, context, false, false).toOwned();
+ url = state.coerceToString(attr.pos, *attr.value, context, false, false).toOwned();
else if (n == "rev") {
// Ugly: unlike fetchGit, here the "rev" attribute can
// be both a revision or a branch/tag name.
- auto value = state.forceStringNoCtx(*attr.value, *attr.pos);
+ auto value = state.forceStringNoCtx(*attr.value, attr.pos);
if (std::regex_match(value.begin(), value.end(), revRegex))
rev = Hash::parseAny(value, htSHA1);
else
ref = value;
}
else if (n == "name")
- name = state.forceStringNoCtx(*attr.value, *attr.pos);
+ name = state.forceStringNoCtx(*attr.value, attr.pos);
else
throw EvalError({
- .msg = hintfmt("unsupported argument '%s' to 'fetchMercurial'", attr.name),
- .errPos = *attr.pos
+ .msg = hintfmt("unsupported argument '%s' to 'fetchMercurial'", state.symbols[attr.name]),
+ .errPos = state.positions[attr.pos]
});
}
if (url.empty())
throw EvalError({
.msg = hintfmt("'url' argument required"),
- .errPos = pos
+ .errPos = state.positions[pos]
});
} else
diff --git a/src/libexpr/primops/fetchTree.cc b/src/libexpr/primops/fetchTree.cc
index f3e3e70d8..84e7f5c02 100644
--- a/src/libexpr/primops/fetchTree.cc
+++ b/src/libexpr/primops/fetchTree.cc
@@ -90,7 +90,7 @@ struct FetchTreeParams {
static void fetchTree(
EvalState & state,
- const Pos & pos,
+ const PosIdx pos,
Value * * args,
Value & v,
std::optional<std::string> type,
@@ -108,46 +108,46 @@ static void fetchTree(
if (auto aType = args[0]->attrs->get(state.sType)) {
if (type)
- throw Error({
+ state.debugThrowLastTrace(EvalError({
.msg = hintfmt("unexpected attribute 'type'"),
- .errPos = pos
- });
- type = state.forceStringNoCtx(*aType->value, *aType->pos);
+ .errPos = state.positions[pos]
+ }));
+ type = state.forceStringNoCtx(*aType->value, aType->pos);
} else if (!type)
- throw Error({
+ state.debugThrowLastTrace(EvalError({
.msg = hintfmt("attribute 'type' is missing in call to 'fetchTree'"),
- .errPos = pos
- });
+ .errPos = state.positions[pos]
+ }));
attrs.emplace("type", type.value());
for (auto & attr : *args[0]->attrs) {
if (attr.name == state.sType) continue;
- state.forceValue(*attr.value, *attr.pos);
+ state.forceValue(*attr.value, attr.pos);
if (attr.value->type() == nPath || attr.value->type() == nString) {
- auto s = state.coerceToString(*attr.pos, *attr.value, context, false, false).toOwned();
- attrs.emplace(attr.name,
- attr.name == "url"
+ auto s = state.coerceToString(attr.pos, *attr.value, context, false, false).toOwned();
+ attrs.emplace(state.symbols[attr.name],
+ state.symbols[attr.name] == "url"
? type == "git"
? fixURIForGit(s, state)
: fixURI(s, state)
: s);
}
else if (attr.value->type() == nBool)
- attrs.emplace(attr.name, Explicit<bool>{attr.value->boolean});
+ attrs.emplace(state.symbols[attr.name], Explicit<bool>{attr.value->boolean});
else if (attr.value->type() == nInt)
- attrs.emplace(attr.name, uint64_t(attr.value->integer));
+ attrs.emplace(state.symbols[attr.name], uint64_t(attr.value->integer));
else
- throw TypeError("fetchTree argument '%s' is %s while a string, Boolean or integer is expected",
- attr.name, showType(*attr.value));
+ state.debugThrowLastTrace(TypeError("fetchTree argument '%s' is %s while a string, Boolean or integer is expected",
+ state.symbols[attr.name], showType(*attr.value)));
}
if (!params.allowNameArgument)
if (auto nameIter = attrs.find("name"); nameIter != attrs.end())
- throw Error({
+ state.debugThrowLastTrace(EvalError({
.msg = hintfmt("attribute 'name' isn’t supported in call to 'fetchTree'"),
- .errPos = pos
- });
+ .errPos = state.positions[pos]
+ }));
input = fetchers::Input::fromAttrs(std::move(attrs));
} else {
@@ -167,7 +167,7 @@ static void fetchTree(
input = lookupInRegistries(state.store, input).first;
if (evalSettings.pureEval && !input.isLocked())
- throw Error("in pure evaluation mode, 'fetchTree' requires a locked input, at %s", pos);
+ state.debugThrowLastTrace(EvalError("in pure evaluation mode, 'fetchTree' requires a locked input, at %s", state.positions[pos]));
auto [tree, input2] = input.fetch(state.store);
@@ -176,7 +176,7 @@ static void fetchTree(
emitTreeAttrs(state, tree, input2, v, params.emptyRevFallback, false);
}
-static void prim_fetchTree(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_fetchTree(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
settings.requireExperimentalFeature(Xp::Flakes);
fetchTree(state, pos, args, v, std::nullopt, FetchTreeParams { .allowNameArgument = false });
@@ -185,7 +185,7 @@ static void prim_fetchTree(EvalState & state, const Pos & pos, Value * * args, V
// FIXME: document
static RegisterPrimOp primop_fetchTree("fetchTree", 1, prim_fetchTree);
-static void fetch(EvalState & state, const Pos & pos, Value * * args, Value & v,
+static void fetch(EvalState & state, const PosIdx pos, Value * * args, Value & v,
const std::string & who, bool unpack, std::string name)
{
std::optional<std::string> url;
@@ -198,25 +198,25 @@ static void fetch(EvalState & state, const Pos & pos, Value * * args, Value & v,
state.forceAttrs(*args[0], pos);
for (auto & attr : *args[0]->attrs) {
- std::string n(attr.name);
+ std::string_view n(state.symbols[attr.name]);
if (n == "url")
- url = state.forceStringNoCtx(*attr.value, *attr.pos);
+ url = state.forceStringNoCtx(*attr.value, attr.pos);
else if (n == "sha256")
- expectedHash = newHashAllowEmpty(state.forceStringNoCtx(*attr.value, *attr.pos), htSHA256);
+ expectedHash = newHashAllowEmpty(state.forceStringNoCtx(*attr.value, attr.pos), htSHA256);
else if (n == "name")
- name = state.forceStringNoCtx(*attr.value, *attr.pos);
+ name = state.forceStringNoCtx(*attr.value, attr.pos);
else
- throw EvalError({
- .msg = hintfmt("unsupported argument '%s' to '%s'", attr.name, who),
- .errPos = *attr.pos
- });
- }
+ state.debugThrowLastTrace(EvalError({
+ .msg = hintfmt("unsupported argument '%s' to '%s'", n, who),
+ .errPos = state.positions[attr.pos]
+ }));
+ }
if (!url)
- throw EvalError({
+ state.debugThrowLastTrace(EvalError({
.msg = hintfmt("'url' argument required"),
- .errPos = pos
- });
+ .errPos = state.positions[pos]
+ }));
} else
url = state.forceStringNoCtx(*args[0], pos);
@@ -228,8 +228,23 @@ static void fetch(EvalState & state, const Pos & pos, Value * * args, Value & v,
name = baseNameOf(*url);
if (evalSettings.pureEval && !expectedHash)
- throw Error("in pure evaluation mode, '%s' requires a 'sha256' argument", who);
+ state.debugThrowLastTrace(EvalError("in pure evaluation mode, '%s' requires a 'sha256' argument", who));
+
+ // early exit if pinned and already in the store
+ if (expectedHash && expectedHash->type == htSHA256) {
+ auto expectedPath =
+ unpack
+ ? state.store->makeFixedOutputPath(FileIngestionMethod::Recursive, *expectedHash, name, {})
+ : state.store->makeFixedOutputPath(FileIngestionMethod::Flat, *expectedHash, name, {});
+
+ if (state.store->isValidPath(expectedPath)) {
+ state.allowAndSetStorePathString(expectedPath, v);
+ return;
+ }
+ }
+ // TODO: fetching may fail, yet the path may be substitutable.
+ // https://github.com/NixOS/nix/issues/4313
auto storePath =
unpack
? fetchers::downloadTarball(state.store, *url, name, (bool) expectedHash).first.storePath
@@ -240,17 +255,14 @@ static void fetch(EvalState & state, const Pos & pos, Value * * args, Value & v,
? state.store->queryPathInfo(storePath)->narHash
: hashFile(htSHA256, state.store->toRealPath(storePath));
if (hash != *expectedHash)
- throw Error((unsigned int) 102, "hash mismatch in file downloaded from '%s':\n specified: %s\n got: %s",
- *url, expectedHash->to_string(Base32, true), hash.to_string(Base32, true));
+ state.debugThrowLastTrace(EvalError((unsigned int) 102, "hash mismatch in file downloaded from '%s':\n specified: %s\n got: %s",
+ *url, expectedHash->to_string(Base32, true), hash.to_string(Base32, true)));
}
- state.allowPath(storePath);
-
- auto path = state.store->printStorePath(storePath);
- v.mkString(path, PathSet({path}));
+ state.allowAndSetStorePathString(storePath, v);
}
-static void prim_fetchurl(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_fetchurl(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
fetch(state, pos, args, v, "fetchurl", false, "");
}
@@ -266,7 +278,7 @@ static RegisterPrimOp primop_fetchurl({
.fun = prim_fetchurl,
});
-static void prim_fetchTarball(EvalState & state, const Pos & pos, Value * * args, Value & v)
+static void prim_fetchTarball(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
fetch(state, pos, args, v, "fetchTarball", true, "source");
}
@@ -317,7 +329,7 @@ static RegisterPrimOp primop_fetchTarball({
.fun = prim_fetchTarball,
});
-static void prim_fetchGit(EvalState &state, const Pos &pos, Value **args, Value &v)
+static void prim_fetchGit(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
fetchTree(state, pos, args, v, "git", FetchTreeParams { .emptyRevFallback = true, .allowNameArgument = true });
}
@@ -352,6 +364,10 @@ static RegisterPrimOp primop_fetchGit({
A Boolean parameter that specifies whether submodules should be
checked out. Defaults to `false`.
+ - shallow\
+ A Boolean parameter that specifies whether fetching a shallow clone
+ is allowed. Defaults to `false`.
+
- allRefs\
Whether to fetch all refs of the repository. With this argument being
true, it's possible to load a `rev` from *any* `ref` (by default only
diff --git a/src/libexpr/primops/fromTOML.cc b/src/libexpr/primops/fromTOML.cc
index dd4280030..9753e2ac9 100644
--- a/src/libexpr/primops/fromTOML.cc
+++ b/src/libexpr/primops/fromTOML.cc
@@ -5,7 +5,7 @@
namespace nix {
-static void prim_fromTOML(EvalState & state, const Pos & pos, Value * * args, Value & val)
+static void prim_fromTOML(EvalState & state, const PosIdx pos, Value * * args, Value & val)
{
auto toml = state.forceStringNoCtx(*args[0], pos);
@@ -73,7 +73,7 @@ static void prim_fromTOML(EvalState & state, const Pos & pos, Value * * args, Va
} catch (std::exception & e) { // TODO: toml::syntax_error
throw EvalError({
.msg = hintfmt("while parsing a TOML string: %s", e.what()),
- .errPos = pos
+ .errPos = state.positions[pos]
});
}
}
diff --git a/src/libexpr/symbol-table.hh b/src/libexpr/symbol-table.hh
index 48d20c29d..288c15602 100644
--- a/src/libexpr/symbol-table.hh
+++ b/src/libexpr/symbol-table.hh
@@ -5,44 +5,32 @@
#include <unordered_map>
#include "types.hh"
+#include "chunked-vector.hh"
namespace nix {
/* Symbol table used by the parser and evaluator to represent and look
up identifiers and attributes efficiently. SymbolTable::create()
converts a string into a symbol. Symbols have the property that
- they can be compared efficiently (using a pointer equality test),
+ they can be compared efficiently (using an equality test),
because the symbol table stores only one copy of each string. */
-class Symbol
+/* This class mainly exists to give us an operator<< for ostreams. We could also
+ return plain strings from SymbolTable, but then we'd have to wrap every
+ instance of a symbol that is fmt()ed, which is inconvenient and error-prone. */
+class SymbolStr
{
-private:
- const std::string * s; // pointer into SymbolTable
- Symbol(const std::string * s) : s(s) { };
friend class SymbolTable;
-public:
- Symbol() : s(0) { };
+private:
+ const std::string * s;
- bool operator == (const Symbol & s2) const
- {
- return s == s2.s;
- }
+ explicit SymbolStr(const std::string & symbol): s(&symbol) {}
- // FIXME: remove
+public:
bool operator == (std::string_view s2) const
{
- return s->compare(s2) == 0;
- }
-
- bool operator != (const Symbol & s2) const
- {
- return s != s2.s;
- }
-
- bool operator < (const Symbol & s2) const
- {
- return s < s2.s;
+ return *s == s2;
}
operator const std::string & () const
@@ -55,51 +43,78 @@ public:
return *s;
}
- bool set() const
- {
- return s;
- }
+ friend std::ostream & operator <<(std::ostream & os, const SymbolStr & symbol);
+};
- bool empty() const
- {
- return s->empty();
- }
+class Symbol
+{
+ friend class SymbolTable;
+
+private:
+ uint32_t id;
+
+ explicit Symbol(uint32_t id): id(id) {}
+
+public:
+ Symbol() : id(0) {}
- friend std::ostream & operator << (std::ostream & str, const Symbol & sym);
+ explicit operator bool() const { return id > 0; }
+
+ bool operator<(const Symbol other) const { return id < other.id; }
+ bool operator==(const Symbol other) const { return id == other.id; }
+ bool operator!=(const Symbol other) const { return id != other.id; }
};
class SymbolTable
{
private:
- std::unordered_map<std::string_view, Symbol> symbols;
- std::list<std::string> store;
+ std::unordered_map<std::string_view, std::pair<const std::string *, uint32_t>> symbols;
+ ChunkedVector<std::string, 8192> store{16};
public:
+
Symbol create(std::string_view s)
{
// Most symbols are looked up more than once, so we trade off insertion performance
// for lookup performance.
// TODO: could probably be done more efficiently with transparent Hash and Equals
// on the original implementation using unordered_set
+ // FIXME: make this thread-safe.
auto it = symbols.find(s);
- if (it != symbols.end()) return it->second;
+ if (it != symbols.end()) return Symbol(it->second.second + 1);
+
+ const auto & [rawSym, idx] = store.add(std::string(s));
+ symbols.emplace(rawSym, std::make_pair(&rawSym, idx));
+ return Symbol(idx + 1);
+ }
- auto & rawSym = store.emplace_back(s);
- return symbols.emplace(rawSym, Symbol(&rawSym)).first->second;
+ std::vector<SymbolStr> resolve(const std::vector<Symbol> & symbols) const
+ {
+ std::vector<SymbolStr> result;
+ result.reserve(symbols.size());
+ for (auto sym : symbols)
+ result.push_back((*this)[sym]);
+ return result;
+ }
+
+ SymbolStr operator[](Symbol s) const
+ {
+ if (s.id == 0 || s.id > store.size())
+ abort();
+ return SymbolStr(store[s.id - 1]);
}
size_t size() const
{
- return symbols.size();
+ return store.size();
}
size_t totalSize() const;
template<typename T>
- void dump(T callback)
+ void dump(T callback) const
{
- for (auto & s : store)
- callback(s);
+ store.forEach(callback);
}
};
diff --git a/src/libexpr/tests/json.cc b/src/libexpr/tests/json.cc
new file mode 100644
index 000000000..f1ea1b197
--- /dev/null
+++ b/src/libexpr/tests/json.cc
@@ -0,0 +1,68 @@
+#include "libexprtests.hh"
+#include "value-to-json.hh"
+
+namespace nix {
+// Testing the conversion to JSON
+
+ class JSONValueTest : public LibExprTest {
+ protected:
+ std::string getJSONValue(Value& value) {
+ std::stringstream ss;
+ PathSet ps;
+ printValueAsJSON(state, true, value, noPos, ss, ps);
+ return ss.str();
+ }
+ };
+
+ TEST_F(JSONValueTest, null) {
+ Value v;
+ v.mkNull();
+ ASSERT_EQ(getJSONValue(v), "null");
+ }
+
+ TEST_F(JSONValueTest, BoolFalse) {
+ Value v;
+ v.mkBool(false);
+ ASSERT_EQ(getJSONValue(v),"false");
+ }
+
+ TEST_F(JSONValueTest, BoolTrue) {
+ Value v;
+ v.mkBool(true);
+ ASSERT_EQ(getJSONValue(v), "true");
+ }
+
+ TEST_F(JSONValueTest, IntPositive) {
+ Value v;
+ v.mkInt(100);
+ ASSERT_EQ(getJSONValue(v), "100");
+ }
+
+ TEST_F(JSONValueTest, IntNegative) {
+ Value v;
+ v.mkInt(-100);
+ ASSERT_EQ(getJSONValue(v), "-100");
+ }
+
+ TEST_F(JSONValueTest, String) {
+ Value v;
+ v.mkString("test");
+ ASSERT_EQ(getJSONValue(v), "\"test\"");
+ }
+
+ TEST_F(JSONValueTest, StringQuotes) {
+ Value v;
+
+ v.mkString("test\"");
+ ASSERT_EQ(getJSONValue(v), "\"test\\\"\"");
+ }
+
+ // The dummy store doesn't support writing files. Fails with this exception message:
+ // C++ exception with description "error: operation 'addToStoreFromDump' is
+ // not supported by store 'dummy'" thrown in the test body.
+ TEST_F(JSONValueTest, DISABLED_Path) {
+ Value v;
+ v.mkPath("test");
+ ASSERT_EQ(getJSONValue(v), "\"/nix/store/g1w7hy3qg1w7hy3qg1w7hy3qg1w7hy3q-x\"");
+ }
+} /* namespace nix */
diff --git a/src/libexpr/tests/libexprtests.hh b/src/libexpr/tests/libexprtests.hh
new file mode 100644
index 000000000..4f6915882
--- /dev/null
+++ b/src/libexpr/tests/libexprtests.hh
@@ -0,0 +1,136 @@
+#include <gtest/gtest.h>
+#include <gmock/gmock.h>
+
+#include "value.hh"
+#include "nixexpr.hh"
+#include "eval.hh"
+#include "eval-inline.hh"
+#include "store-api.hh"
+
+
+namespace nix {
+ class LibExprTest : public ::testing::Test {
+ public:
+ static void SetUpTestSuite() {
+ initGC();
+ }
+
+ protected:
+ LibExprTest()
+ : store(openStore("dummy://"))
+ , state({}, store)
+ {
+ }
+ Value eval(std::string input, bool forceValue = true) {
+ Value v;
+ Expr * e = state.parseExprFromString(input, "");
+ assert(e);
+ state.eval(e, v);
+ if (forceValue)
+ state.forceValue(v, noPos);
+ return v;
+ }
+
+ Symbol createSymbol(const char * value) {
+ return state.symbols.create(value);
+ }
+
+ ref<Store> store;
+ EvalState state;
+ };
+
+ MATCHER(IsListType, "") {
+ return arg != nList;
+ }
+
+ MATCHER(IsList, "") {
+ return arg.type() == nList;
+ }
+
+ MATCHER(IsString, "") {
+ return arg.type() == nString;
+ }
+
+ MATCHER(IsNull, "") {
+ return arg.type() == nNull;
+ }
+
+ MATCHER(IsThunk, "") {
+ return arg.type() == nThunk;
+ }
+
+ MATCHER(IsAttrs, "") {
+ return arg.type() == nAttrs;
+ }
+
+ MATCHER_P(IsStringEq, s, fmt("The string is equal to \"%1%\"", s)) {
+ if (arg.type() != nString) {
+ return false;
+ }
+ return std::string_view(arg.string.s) == s;
+ }
+
+ MATCHER_P(IsIntEq, v, fmt("The string is equal to \"%1%\"", v)) {
+ if (arg.type() != nInt) {
+ return false;
+ }
+ return arg.integer == v;
+ }
+
+ MATCHER_P(IsFloatEq, v, fmt("The float is equal to \"%1%\"", v)) {
+ if (arg.type() != nFloat) {
+ return false;
+ }
+ return arg.fpoint == v;
+ }
+
+ MATCHER(IsTrue, "") {
+ if (arg.type() != nBool) {
+ return false;
+ }
+ return arg.boolean == true;
+ }
+
+ MATCHER(IsFalse, "") {
+ if (arg.type() != nBool) {
+ return false;
+ }
+ return arg.boolean == false;
+ }
+
+ MATCHER_P(IsPathEq, p, fmt("Is a path equal to \"%1%\"", p)) {
+ if (arg.type() != nPath) {
+ *result_listener << "Expected a path got " << arg.type();
+ return false;
+ } else if (std::string_view(arg.string.s) != p) {
+ *result_listener << "Expected a path that equals \"" << p << "\" but got: " << arg.string.s;
+ return false;
+ }
+ return true;
+ }
+
+
+ MATCHER_P(IsListOfSize, n, fmt("Is a list of size [%1%]", n)) {
+ if (arg.type() != nList) {
+ *result_listener << "Expected list got " << arg.type();
+ return false;
+ } else if (arg.listSize() != (size_t)n) {
+ *result_listener << "Expected as list of size " << n << " got " << arg.listSize();
+ return false;
+ }
+ return true;
+ }
+
+ MATCHER_P(IsAttrsOfSize, n, fmt("Is a set of size [%1%]", n)) {
+ if (arg.type() != nAttrs) {
+ *result_listener << "Expexted set got " << arg.type();
+ return false;
+ } else if (arg.attrs->size() != (size_t)n) {
+ *result_listener << "Expected a set with " << n << " attributes but got " << arg.attrs->size();
+ return false;
+ }
+ return true;
+ }
+
+
+} /* namespace nix */
diff --git a/src/libexpr/tests/local.mk b/src/libexpr/tests/local.mk
new file mode 100644
index 000000000..b95980cab
--- /dev/null
+++ b/src/libexpr/tests/local.mk
@@ -0,0 +1,15 @@
+check: libexpr-tests_RUN
+
+programs += libexpr-tests
+
+libexpr-tests_DIR := $(d)
+
+libexpr-tests_INSTALL_DIR :=
+
+libexpr-tests_SOURCES := $(wildcard $(d)/*.cc)
+
+libexpr-tests_CXXFLAGS += -I src/libexpr -I src/libutil -I src/libstore -I src/libexpr/tests
+
+libexpr-tests_LIBS = libexpr libutil libstore libfetchers
+
+libexpr-tests_LDFLAGS := $(GTEST_LIBS) -lgmock
diff --git a/src/libexpr/tests/primops.cc b/src/libexpr/tests/primops.cc
new file mode 100644
index 000000000..16cf66d2c
--- /dev/null
+++ b/src/libexpr/tests/primops.cc
@@ -0,0 +1,839 @@
+#include <gmock/gmock.h>
+#include <gtest/gtest.h>
+
+#include "libexprtests.hh"
+
+namespace nix {
+ class CaptureLogger : public Logger
+ {
+ std::ostringstream oss;
+
+ public:
+ CaptureLogger() {}
+
+ std::string get() const {
+ return oss.str();
+ }
+
+ void log(Verbosity lvl, const FormatOrString & fs) override {
+ oss << fs.s << std::endl;
+ }
+
+ void logEI(const ErrorInfo & ei) override {
+ showErrorInfo(oss, ei, loggerSettings.showTrace.get());
+ }
+ };
+
+ class CaptureLogging {
+ Logger * oldLogger;
+ std::unique_ptr<CaptureLogger> tempLogger;
+ public:
+ CaptureLogging() : tempLogger(std::make_unique<CaptureLogger>()) {
+ oldLogger = logger;
+ logger = tempLogger.get();
+ }
+
+ ~CaptureLogging() {
+ logger = oldLogger;
+ }
+
+ std::string get() const {
+ return tempLogger->get();
+ }
+ };
+
+
+ // Testing eval of PrimOp's
+ class PrimOpTest : public LibExprTest {};
+
+
+ TEST_F(PrimOpTest, throw) {
+ ASSERT_THROW(eval("throw \"foo\""), ThrownError);
+ }
+
+ TEST_F(PrimOpTest, abort) {
+ ASSERT_THROW(eval("abort \"abort\""), Abort);
+ }
+
+ TEST_F(PrimOpTest, ceil) {
+ auto v = eval("builtins.ceil 1.9");
+ ASSERT_THAT(v, IsIntEq(2));
+ }
+
+ TEST_F(PrimOpTest, floor) {
+ auto v = eval("builtins.floor 1.9");
+ ASSERT_THAT(v, IsIntEq(1));
+ }
+
+ TEST_F(PrimOpTest, tryEvalFailure) {
+ auto v = eval("builtins.tryEval (throw \"\")");
+ ASSERT_THAT(v, IsAttrsOfSize(2));
+ auto s = createSymbol("success");
+ auto p = v.attrs->get(s);
+ ASSERT_NE(p, nullptr);
+ ASSERT_THAT(*p->value, IsFalse());
+ }
+
+ TEST_F(PrimOpTest, tryEvalSuccess) {
+ auto v = eval("builtins.tryEval 123");
+ ASSERT_THAT(v, IsAttrs());
+ auto s = createSymbol("success");
+ auto p = v.attrs->get(s);
+ ASSERT_NE(p, nullptr);
+ ASSERT_THAT(*p->value, IsTrue());
+ s = createSymbol("value");
+ p = v.attrs->get(s);
+ ASSERT_NE(p, nullptr);
+ ASSERT_THAT(*p->value, IsIntEq(123));
+ }
+
+ TEST_F(PrimOpTest, getEnv) {
+ setenv("_NIX_UNIT_TEST_ENV_VALUE", "test value", 1);
+ auto v = eval("builtins.getEnv \"_NIX_UNIT_TEST_ENV_VALUE\"");
+ ASSERT_THAT(v, IsStringEq("test value"));
+ }
+
+ TEST_F(PrimOpTest, seq) {
+ ASSERT_THROW(eval("let x = throw \"test\"; in builtins.seq x { }"), ThrownError);
+ }
+
+ TEST_F(PrimOpTest, seqNotDeep) {
+ auto v = eval("let x = { z = throw \"test\"; }; in builtins.seq x { }");
+ ASSERT_THAT(v, IsAttrs());
+ }
+
+ TEST_F(PrimOpTest, deepSeq) {
+ ASSERT_THROW(eval("let x = { z = throw \"test\"; }; in builtins.deepSeq x { }"), ThrownError);
+ }
+
+ TEST_F(PrimOpTest, trace) {
+ CaptureLogging l;
+ auto v = eval("builtins.trace \"test string 123\" 123");
+ ASSERT_THAT(v, IsIntEq(123));
+ auto text = l.get();
+ ASSERT_NE(text.find("test string 123"), std::string::npos);
+ }
+
+ TEST_F(PrimOpTest, placeholder) {
+ auto v = eval("builtins.placeholder \"out\"");
+ ASSERT_THAT(v, IsStringEq("/1rz4g4znpzjwh1xymhjpm42vipw92pr73vdgl6xs1hycac8kf2n9"));
+ }
+
+ TEST_F(PrimOpTest, baseNameOf) {
+ auto v = eval("builtins.baseNameOf /some/path");
+ ASSERT_THAT(v, IsStringEq("path"));
+ }
+
+ TEST_F(PrimOpTest, dirOf) {
+ auto v = eval("builtins.dirOf /some/path");
+ ASSERT_THAT(v, IsPathEq("/some"));
+ }
+
+ TEST_F(PrimOpTest, attrValues) {
+ auto v = eval("builtins.attrValues { x = \"foo\"; a = 1; }");
+ ASSERT_THAT(v, IsListOfSize(2));
+ ASSERT_THAT(*v.listElems()[0], IsIntEq(1));
+ ASSERT_THAT(*v.listElems()[1], IsStringEq("foo"));
+ }
+
+ TEST_F(PrimOpTest, getAttr) {
+ auto v = eval("builtins.getAttr \"x\" { x = \"foo\"; }");
+ ASSERT_THAT(v, IsStringEq("foo"));
+ }
+
+ TEST_F(PrimOpTest, getAttrNotFound) {
+ // FIXME: TypeError is really bad here, also the error wording is worse
+ // than on Nix <=2.3
+ ASSERT_THROW(eval("builtins.getAttr \"y\" { }"), TypeError);
+ }
+
+ TEST_F(PrimOpTest, unsafeGetAttrPos) {
+ // The `y` attribute is at position
+ const char* expr = "builtins.unsafeGetAttrPos \"y\" { y = \"x\"; }";
+ auto v = eval(expr);
+ ASSERT_THAT(v, IsAttrsOfSize(3));
+
+ auto file = v.attrs->find(createSymbol("file"));
+ ASSERT_NE(file, nullptr);
+ // FIXME: The file when running these tests is the input string?!?
+ ASSERT_THAT(*file->value, IsStringEq(expr));
+
+ auto line = v.attrs->find(createSymbol("line"));
+ ASSERT_NE(line, nullptr);
+ ASSERT_THAT(*line->value, IsIntEq(1));
+
+ auto column = v.attrs->find(createSymbol("column"));
+ ASSERT_NE(column, nullptr);
+ ASSERT_THAT(*column->value, IsIntEq(33));
+ }
+
+ TEST_F(PrimOpTest, hasAttr) {
+ auto v = eval("builtins.hasAttr \"x\" { x = 1; }");
+ ASSERT_THAT(v, IsTrue());
+ }
+
+ TEST_F(PrimOpTest, hasAttrNotFound) {
+ auto v = eval("builtins.hasAttr \"x\" { }");
+ ASSERT_THAT(v, IsFalse());
+ }
+
+ TEST_F(PrimOpTest, isAttrs) {
+ auto v = eval("builtins.isAttrs {}");
+ ASSERT_THAT(v, IsTrue());
+ }
+
+ TEST_F(PrimOpTest, isAttrsFalse) {
+ auto v = eval("builtins.isAttrs null");
+ ASSERT_THAT(v, IsFalse());
+ }
+
+ TEST_F(PrimOpTest, removeAttrs) {
+ auto v = eval("builtins.removeAttrs { x = 1; } [\"x\"]");
+ ASSERT_THAT(v, IsAttrsOfSize(0));
+ }
+
+ TEST_F(PrimOpTest, removeAttrsRetains) {
+ auto v = eval("builtins.removeAttrs { x = 1; y = 2; } [\"x\"]");
+ ASSERT_THAT(v, IsAttrsOfSize(1));
+ ASSERT_NE(v.attrs->find(createSymbol("y")), nullptr);
+ }
+
+ TEST_F(PrimOpTest, listToAttrsEmptyList) {
+ auto v = eval("builtins.listToAttrs []");
+ ASSERT_THAT(v, IsAttrsOfSize(0));
+ ASSERT_EQ(v.type(), nAttrs);
+ ASSERT_EQ(v.attrs->size(), 0);
+ }
+
+ TEST_F(PrimOpTest, listToAttrsNotFieldName) {
+ ASSERT_THROW(eval("builtins.listToAttrs [{}]"), Error);
+ }
+
+ TEST_F(PrimOpTest, listToAttrs) {
+ auto v = eval("builtins.listToAttrs [ { name = \"key\"; value = 123; } ]");
+ ASSERT_THAT(v, IsAttrsOfSize(1));
+ auto key = v.attrs->find(createSymbol("key"));
+ ASSERT_NE(key, nullptr);
+ ASSERT_THAT(*key->value, IsIntEq(123));
+ }
+
+ TEST_F(PrimOpTest, intersectAttrs) {
+ auto v = eval("builtins.intersectAttrs { a = 1; b = 2; } { b = 3; c = 4; }");
+ ASSERT_THAT(v, IsAttrsOfSize(1));
+ auto b = v.attrs->find(createSymbol("b"));
+ ASSERT_NE(b, nullptr);
+ ASSERT_THAT(*b->value, IsIntEq(3));
+ }
+
+ TEST_F(PrimOpTest, catAttrs) {
+ auto v = eval("builtins.catAttrs \"a\" [{a = 1;} {b = 0;} {a = 2;}]");
+ ASSERT_THAT(v, IsListOfSize(2));
+ ASSERT_THAT(*v.listElems()[0], IsIntEq(1));
+ ASSERT_THAT(*v.listElems()[1], IsIntEq(2));
+ }
+
+ TEST_F(PrimOpTest, functionArgs) {
+ auto v = eval("builtins.functionArgs ({ x, y ? 123}: 1)");
+ ASSERT_THAT(v, IsAttrsOfSize(2));
+
+ auto x = v.attrs->find(createSymbol("x"));
+ ASSERT_NE(x, nullptr);
+ ASSERT_THAT(*x->value, IsFalse());
+
+ auto y = v.attrs->find(createSymbol("y"));
+ ASSERT_NE(y, nullptr);
+ ASSERT_THAT(*y->value, IsTrue());
+ }
+
+ TEST_F(PrimOpTest, mapAttrs) {
+ auto v = eval("builtins.mapAttrs (name: value: value * 10) { a = 1; b = 2; }");
+ ASSERT_THAT(v, IsAttrsOfSize(2));
+
+ auto a = v.attrs->find(createSymbol("a"));
+ ASSERT_NE(a, nullptr);
+ ASSERT_THAT(*a->value, IsThunk());
+ state.forceValue(*a->value, noPos);
+ ASSERT_THAT(*a->value, IsIntEq(10));
+
+ auto b = v.attrs->find(createSymbol("b"));
+ ASSERT_NE(b, nullptr);
+ ASSERT_THAT(*b->value, IsThunk());
+ state.forceValue(*b->value, noPos);
+ ASSERT_THAT(*b->value, IsIntEq(20));
+ }
+
+ TEST_F(PrimOpTest, isList) {
+ auto v = eval("builtins.isList []");
+ ASSERT_THAT(v, IsTrue());
+ }
+
+ TEST_F(PrimOpTest, isListFalse) {
+ auto v = eval("builtins.isList null");
+ ASSERT_THAT(v, IsFalse());
+ }
+
+ TEST_F(PrimOpTest, elemtAt) {
+ auto v = eval("builtins.elemAt [0 1 2 3] 3");
+ ASSERT_THAT(v, IsIntEq(3));
+ }
+
+ TEST_F(PrimOpTest, elemtAtOutOfBounds) {
+ ASSERT_THROW(eval("builtins.elemAt [0 1 2 3] 5"), Error);
+ }
+
+ TEST_F(PrimOpTest, head) {
+ auto v = eval("builtins.head [ 3 2 1 0 ]");
+ ASSERT_THAT(v, IsIntEq(3));
+ }
+
+ TEST_F(PrimOpTest, headEmpty) {
+ ASSERT_THROW(eval("builtins.head [ ]"), Error);
+ }
+
+ TEST_F(PrimOpTest, headWrongType) {
+ ASSERT_THROW(eval("builtins.head { }"), Error);
+ }
+
+ TEST_F(PrimOpTest, tail) {
+ auto v = eval("builtins.tail [ 3 2 1 0 ]");
+ ASSERT_THAT(v, IsListOfSize(3));
+ for (const auto [n, elem] : enumerate(v.listItems()))
+ ASSERT_THAT(*elem, IsIntEq(2 - static_cast<int>(n)));
+ }
+
+ TEST_F(PrimOpTest, tailEmpty) {
+ ASSERT_THROW(eval("builtins.tail []"), Error);
+ }
+
+ TEST_F(PrimOpTest, map) {
+ auto v = eval("map (x: \"foo\" + x) [ \"bar\" \"bla\" \"abc\" ]");
+ ASSERT_THAT(v, IsListOfSize(3));
+ auto elem = v.listElems()[0];
+ ASSERT_THAT(*elem, IsThunk());
+ state.forceValue(*elem, noPos);
+ ASSERT_THAT(*elem, IsStringEq("foobar"));
+
+ elem = v.listElems()[1];
+ ASSERT_THAT(*elem, IsThunk());
+ state.forceValue(*elem, noPos);
+ ASSERT_THAT(*elem, IsStringEq("foobla"));
+
+ elem = v.listElems()[2];
+ ASSERT_THAT(*elem, IsThunk());
+ state.forceValue(*elem, noPos);
+ ASSERT_THAT(*elem, IsStringEq("fooabc"));
+ }
+
+ TEST_F(PrimOpTest, filter) {
+ auto v = eval("builtins.filter (x: x == 2) [ 3 2 3 2 3 2 ]");
+ ASSERT_THAT(v, IsListOfSize(3));
+ for (const auto elem : v.listItems())
+ ASSERT_THAT(*elem, IsIntEq(2));
+ }
+
+ TEST_F(PrimOpTest, elemTrue) {
+ auto v = eval("builtins.elem 3 [ 1 2 3 4 5 ]");
+ ASSERT_THAT(v, IsTrue());
+ }
+
+ TEST_F(PrimOpTest, elemFalse) {
+ auto v = eval("builtins.elem 6 [ 1 2 3 4 5 ]");
+ ASSERT_THAT(v, IsFalse());
+ }
+
+ TEST_F(PrimOpTest, concatLists) {
+ auto v = eval("builtins.concatLists [[1 2] [3 4]]");
+ ASSERT_THAT(v, IsListOfSize(4));
+ for (const auto [i, elem] : enumerate(v.listItems()))
+ ASSERT_THAT(*elem, IsIntEq(static_cast<int>(i)+1));
+ }
+
+ TEST_F(PrimOpTest, length) {
+ auto v = eval("builtins.length [ 1 2 3 ]");
+ ASSERT_THAT(v, IsIntEq(3));
+ }
+
+ TEST_F(PrimOpTest, foldStrict) {
+ auto v = eval("builtins.foldl' (a: b: a + b) 0 [1 2 3]");
+ ASSERT_THAT(v, IsIntEq(6));
+ }
+
+ TEST_F(PrimOpTest, anyTrue) {
+ auto v = eval("builtins.any (x: x == 2) [ 1 2 3 ]");
+ ASSERT_THAT(v, IsTrue());
+ }
+
+ TEST_F(PrimOpTest, anyFalse) {
+ auto v = eval("builtins.any (x: x == 5) [ 1 2 3 ]");
+ ASSERT_THAT(v, IsFalse());
+ }
+
+ TEST_F(PrimOpTest, allTrue) {
+ auto v = eval("builtins.all (x: x > 0) [ 1 2 3 ]");
+ ASSERT_THAT(v, IsTrue());
+ }
+
+ TEST_F(PrimOpTest, allFalse) {
+ auto v = eval("builtins.all (x: x <= 0) [ 1 2 3 ]");
+ ASSERT_THAT(v, IsFalse());
+ }
+
+ TEST_F(PrimOpTest, genList) {
+ auto v = eval("builtins.genList (x: x + 1) 3");
+ ASSERT_EQ(v.type(), nList);
+ ASSERT_EQ(v.listSize(), 3);
+ for (const auto [i, elem] : enumerate(v.listItems())) {
+ ASSERT_THAT(*elem, IsThunk());
+ state.forceValue(*elem, noPos);
+ ASSERT_THAT(*elem, IsIntEq(static_cast<int>(i)+1));
+ }
+ }
+
+ TEST_F(PrimOpTest, sortLessThan) {
+ auto v = eval("builtins.sort builtins.lessThan [ 483 249 526 147 42 77 ]");
+ ASSERT_EQ(v.type(), nList);
+ ASSERT_EQ(v.listSize(), 6);
+
+ const std::vector<int> numbers = { 42, 77, 147, 249, 483, 526 };
+ for (const auto [n, elem] : enumerate(v.listItems()))
+ ASSERT_THAT(*elem, IsIntEq(numbers[n]));
+ }
+
+ TEST_F(PrimOpTest, partition) {
+ auto v = eval("builtins.partition (x: x > 10) [1 23 9 3 42]");
+ ASSERT_THAT(v, IsAttrsOfSize(2));
+
+ auto right = v.attrs->get(createSymbol("right"));
+ ASSERT_NE(right, nullptr);
+ ASSERT_THAT(*right->value, IsListOfSize(2));
+ ASSERT_THAT(*right->value->listElems()[0], IsIntEq(23));
+ ASSERT_THAT(*right->value->listElems()[1], IsIntEq(42));
+
+ auto wrong = v.attrs->get(createSymbol("wrong"));
+ ASSERT_NE(wrong, nullptr);
+ ASSERT_EQ(wrong->value->type(), nList);
+ ASSERT_EQ(wrong->value->listSize(), 3);
+ ASSERT_THAT(*wrong->value, IsListOfSize(3));
+ ASSERT_THAT(*wrong->value->listElems()[0], IsIntEq(1));
+ ASSERT_THAT(*wrong->value->listElems()[1], IsIntEq(9));
+ ASSERT_THAT(*wrong->value->listElems()[2], IsIntEq(3));
+ }
+
+ TEST_F(PrimOpTest, concatMap) {
+ auto v = eval("builtins.concatMap (x: x ++ [0]) [ [1 2] [3 4] ]");
+ ASSERT_EQ(v.type(), nList);
+ ASSERT_EQ(v.listSize(), 6);
+
+ const std::vector<int> numbers = { 1, 2, 0, 3, 4, 0 };
+ for (const auto [n, elem] : enumerate(v.listItems()))
+ ASSERT_THAT(*elem, IsIntEq(numbers[n]));
+ }
+
+ TEST_F(PrimOpTest, addInt) {
+ auto v = eval("builtins.add 3 5");
+ ASSERT_THAT(v, IsIntEq(8));
+ }
+
+ TEST_F(PrimOpTest, addFloat) {
+ auto v = eval("builtins.add 3.0 5.0");
+ ASSERT_THAT(v, IsFloatEq(8.0));
+ }
+
+ TEST_F(PrimOpTest, addFloatToInt) {
+ auto v = eval("builtins.add 3.0 5");
+ ASSERT_THAT(v, IsFloatEq(8.0));
+
+ v = eval("builtins.add 3 5.0");
+ ASSERT_THAT(v, IsFloatEq(8.0));
+ }
+
+ TEST_F(PrimOpTest, subInt) {
+ auto v = eval("builtins.sub 5 2");
+ ASSERT_THAT(v, IsIntEq(3));
+ }
+
+ TEST_F(PrimOpTest, subFloat) {
+ auto v = eval("builtins.sub 5.0 2.0");
+ ASSERT_THAT(v, IsFloatEq(3.0));
+ }
+
+ TEST_F(PrimOpTest, subFloatFromInt) {
+ auto v = eval("builtins.sub 5.0 2");
+ ASSERT_THAT(v, IsFloatEq(3.0));
+
+ v = eval("builtins.sub 4 2.0");
+ ASSERT_THAT(v, IsFloatEq(2.0));
+ }
+
+ TEST_F(PrimOpTest, mulInt) {
+ auto v = eval("builtins.mul 3 5");
+ ASSERT_THAT(v, IsIntEq(15));
+ }
+
+ TEST_F(PrimOpTest, mulFloat) {
+ auto v = eval("builtins.mul 3.0 5.0");
+ ASSERT_THAT(v, IsFloatEq(15.0));
+ }
+
+ TEST_F(PrimOpTest, mulFloatMixed) {
+ auto v = eval("builtins.mul 3 5.0");
+ ASSERT_THAT(v, IsFloatEq(15.0));
+
+ v = eval("builtins.mul 2.0 5");
+ ASSERT_THAT(v, IsFloatEq(10.0));
+ }
+
+ TEST_F(PrimOpTest, divInt) {
+ auto v = eval("builtins.div 5 (-1)");
+ ASSERT_THAT(v, IsIntEq(-5));
+ }
+
+ TEST_F(PrimOpTest, divIntZero) {
+ ASSERT_THROW(eval("builtins.div 5 0"), EvalError);
+ }
+
+ TEST_F(PrimOpTest, divFloat) {
+ auto v = eval("builtins.div 5.0 (-1)");
+ ASSERT_THAT(v, IsFloatEq(-5.0));
+ }
+
+ TEST_F(PrimOpTest, divFloatZero) {
+ ASSERT_THROW(eval("builtins.div 5.0 0.0"), EvalError);
+ }
+
+ TEST_F(PrimOpTest, bitOr) {
+ auto v = eval("builtins.bitOr 1 2");
+ ASSERT_THAT(v, IsIntEq(3));
+ }
+
+ TEST_F(PrimOpTest, bitXor) {
+ auto v = eval("builtins.bitXor 3 2");
+ ASSERT_THAT(v, IsIntEq(1));
+ }
+
+ TEST_F(PrimOpTest, lessThanFalse) {
+ auto v = eval("builtins.lessThan 3 1");
+ ASSERT_THAT(v, IsFalse());
+ }
+
+ TEST_F(PrimOpTest, lessThanTrue) {
+ auto v = eval("builtins.lessThan 1 3");
+ ASSERT_THAT(v, IsTrue());
+ }
+
+ TEST_F(PrimOpTest, toStringAttrsThrows) {
+ ASSERT_THROW(eval("builtins.toString {}"), EvalError);
+ }
+
+ TEST_F(PrimOpTest, toStringLambdaThrows) {
+ ASSERT_THROW(eval("builtins.toString (x: x)"), EvalError);
+ }
+
+ class ToStringPrimOpTest :
+ public PrimOpTest,
+ public testing::WithParamInterface<std::tuple<std::string, std::string_view>>
+ {};
+
+ TEST_P(ToStringPrimOpTest, toString) {
+ const auto [input, output] = GetParam();
+ auto v = eval(input);
+ ASSERT_THAT(v, IsStringEq(output));
+ }
+
+#define CASE(input, output) (std::make_tuple(std::string_view("builtins.toString " input), std::string_view(output)))
+ INSTANTIATE_TEST_SUITE_P(
+ toString,
+ ToStringPrimOpTest,
+ testing::Values(
+ CASE(R"("foo")", "foo"),
+ CASE(R"(1)", "1"),
+ CASE(R"([1 2 3])", "1 2 3"),
+ CASE(R"(.123)", "0.123000"),
+ CASE(R"(true)", "1"),
+ CASE(R"(false)", ""),
+ CASE(R"(null)", ""),
+ CASE(R"({ v = "bar"; __toString = self: self.v; })", "bar"),
+ CASE(R"({ v = "bar"; __toString = self: self.v; outPath = "foo"; })", "bar"),
+ CASE(R"({ outPath = "foo"; })", "foo"),
+ CASE(R"(./test)", "/test")
+ )
+ );
+#undef CASE
+
+ TEST_F(PrimOpTest, substring){
+ auto v = eval("builtins.substring 0 3 \"nixos\"");
+ ASSERT_THAT(v, IsStringEq("nix"));
+ }
+
+ TEST_F(PrimOpTest, substringSmallerString){
+ auto v = eval("builtins.substring 0 3 \"n\"");
+ ASSERT_THAT(v, IsStringEq("n"));
+ }
+
+ TEST_F(PrimOpTest, substringEmptyString){
+ auto v = eval("builtins.substring 1 3 \"\"");
+ ASSERT_THAT(v, IsStringEq(""));
+ }
+
+ TEST_F(PrimOpTest, stringLength) {
+ auto v = eval("builtins.stringLength \"123\"");
+ ASSERT_THAT(v, IsIntEq(3));
+ }
+ TEST_F(PrimOpTest, hashStringMd5) {
+ auto v = eval("builtins.hashString \"md5\" \"asdf\"");
+ ASSERT_THAT(v, IsStringEq("912ec803b2ce49e4a541068d495ab570"));
+ }
+
+ TEST_F(PrimOpTest, hashStringSha1) {
+ auto v = eval("builtins.hashString \"sha1\" \"asdf\"");
+ ASSERT_THAT(v, IsStringEq("3da541559918a808c2402bba5012f6c60b27661c"));
+ }
+
+ TEST_F(PrimOpTest, hashStringSha256) {
+ auto v = eval("builtins.hashString \"sha256\" \"asdf\"");
+ ASSERT_THAT(v, IsStringEq("f0e4c2f76c58916ec258f246851bea091d14d4247a2fc3e18694461b1816e13b"));
+ }
+
+ TEST_F(PrimOpTest, hashStringSha512) {
+ auto v = eval("builtins.hashString \"sha512\" \"asdf\"");
+ ASSERT_THAT(v, IsStringEq("401b09eab3c013d4ca54922bb802bec8fd5318192b0a75f201d8b3727429080fb337591abd3e44453b954555b7a0812e1081c39b740293f765eae731f5a65ed1"));
+ }
+
+ TEST_F(PrimOpTest, hashStringInvalidHashType) {
+ ASSERT_THROW(eval("builtins.hashString \"foobar\" \"asdf\""), Error);
+ }
+
+ TEST_F(PrimOpTest, nixPath) {
+ auto v = eval("builtins.nixPath");
+ ASSERT_EQ(v.type(), nList);
+ // We can't test much more as currently the EvalSettings are a global
+ // that we can't easily swap / replace
+ }
+
+ TEST_F(PrimOpTest, langVersion) {
+ auto v = eval("builtins.langVersion");
+ ASSERT_EQ(v.type(), nInt);
+ }
+
+ TEST_F(PrimOpTest, storeDir) {
+ auto v = eval("builtins.storeDir");
+ ASSERT_THAT(v, IsStringEq("/nix/store"));
+ }
+
+ TEST_F(PrimOpTest, nixVersion) {
+ auto v = eval("builtins.nixVersion");
+ ASSERT_THAT(v, IsStringEq(nixVersion));
+ }
+
+ TEST_F(PrimOpTest, currentSystem) {
+ auto v = eval("builtins.currentSystem");
+ ASSERT_THAT(v, IsStringEq(settings.thisSystem.get()));
+ }
+
+ TEST_F(PrimOpTest, derivation) {
+ auto v = eval("derivation");
+ ASSERT_EQ(v.type(), nFunction);
+ ASSERT_TRUE(v.isLambda());
+ ASSERT_NE(v.lambda.fun, nullptr);
+ ASSERT_TRUE(v.lambda.fun->hasFormals());
+ }
+
+ TEST_F(PrimOpTest, currentTime) {
+ auto v = eval("builtins.currentTime");
+ ASSERT_EQ(v.type(), nInt);
+ ASSERT_TRUE(v.integer > 0);
+ }
+
+ TEST_F(PrimOpTest, splitVersion) {
+ auto v = eval("builtins.splitVersion \"1.2.3git\"");
+ ASSERT_THAT(v, IsListOfSize(4));
+
+ const std::vector<std::string_view> strings = { "1", "2", "3", "git" };
+ for (const auto [n, p] : enumerate(v.listItems()))
+ ASSERT_THAT(*p, IsStringEq(strings[n]));
+ }
+
+ class CompareVersionsPrimOpTest :
+ public PrimOpTest,
+ public testing::WithParamInterface<std::tuple<std::string, const int>>
+ {};
+
+ TEST_P(CompareVersionsPrimOpTest, compareVersions) {
+ auto [expression, expectation] = GetParam();
+ auto v = eval(expression);
+ ASSERT_THAT(v, IsIntEq(expectation));
+ }
+
+#define CASE(a, b, expected) (std::make_tuple("builtins.compareVersions \"" #a "\" \"" #b "\"", expected))
+ INSTANTIATE_TEST_SUITE_P(
+ compareVersions,
+ CompareVersionsPrimOpTest,
+ testing::Values(
+ // The first two are weird cases. Intuition tells they should
+ // be the same but they aren't.
+ CASE(1.0, 1.0.0, -1),
+ CASE(1.0.0, 1.0, 1),
+ // the following are from the nix-env manual:
+ CASE(1.0, 2.3, -1),
+ CASE(2.1, 2.3, -1),
+ CASE(2.3, 2.3, 0),
+ CASE(2.5, 2.3, 1),
+ CASE(3.1, 2.3, 1),
+ CASE(2.3.1, 2.3, 1),
+ CASE(2.3.1, 2.3a, 1),
+ CASE(2.3pre1, 2.3, -1),
+ CASE(2.3pre3, 2.3pre12, -1),
+ CASE(2.3a, 2.3c, -1),
+ CASE(2.3pre1, 2.3c, -1),
+ CASE(2.3pre1, 2.3q, -1)
+ )
+ );
+#undef CASE
+
+
+ class ParseDrvNamePrimOpTest :
+ public PrimOpTest,
+ public testing::WithParamInterface<std::tuple<std::string, std::string_view, std::string_view>>
+ {};
+
+ TEST_P(ParseDrvNamePrimOpTest, parseDrvName) {
+ auto [input, expectedName, expectedVersion] = GetParam();
+ const auto expr = fmt("builtins.parseDrvName \"%1%\"", input);
+ auto v = eval(expr);
+ ASSERT_THAT(v, IsAttrsOfSize(2));
+
+ auto name = v.attrs->find(createSymbol("name"));
+ ASSERT_TRUE(name);
+ ASSERT_THAT(*name->value, IsStringEq(expectedName));
+
+ auto version = v.attrs->find(createSymbol("version"));
+ ASSERT_TRUE(version);
+ ASSERT_THAT(*version->value, IsStringEq(expectedVersion));
+ }
+
+ INSTANTIATE_TEST_SUITE_P(
+ parseDrvName,
+ ParseDrvNamePrimOpTest,
+ testing::Values(
+ std::make_tuple("nix-0.12pre12876", "nix", "0.12pre12876"),
+ std::make_tuple("a-b-c-1234pre5+git", "a-b-c", "1234pre5+git")
+ )
+ );
+
+ TEST_F(PrimOpTest, replaceStrings) {
+ // FIXME: add a test that verifies the string context is as expected
+ auto v = eval("builtins.replaceStrings [\"oo\" \"a\"] [\"a\" \"i\"] \"foobar\"");
+ ASSERT_EQ(v.type(), nString);
+ ASSERT_EQ(v.string.s, std::string_view("fabir"));
+ }
+
+ TEST_F(PrimOpTest, concatStringsSep) {
+ // FIXME: add a test that verifies the string context is as expected
+ auto v = eval("builtins.concatStringsSep \"%\" [\"foo\" \"bar\" \"baz\"]");
+ ASSERT_EQ(v.type(), nString);
+ ASSERT_EQ(std::string_view(v.string.s), "foo%bar%baz");
+ }
+
+ TEST_F(PrimOpTest, split1) {
+ // v = [ "" [ "a" ] "c" ]
+ auto v = eval("builtins.split \"(a)b\" \"abc\"");
+ ASSERT_THAT(v, IsListOfSize(3));
+
+ ASSERT_THAT(*v.listElems()[0], IsStringEq(""));
+
+ ASSERT_THAT(*v.listElems()[1], IsListOfSize(1));
+ ASSERT_THAT(*v.listElems()[1]->listElems()[0], IsStringEq("a"));
+
+ ASSERT_THAT(*v.listElems()[2], IsStringEq("c"));
+ }
+
+ TEST_F(PrimOpTest, split2) {
+ // v is expected to be a list [ "" [ "a" ] "b" [ "c"] "" ]
+ auto v = eval("builtins.split \"([ac])\" \"abc\"");
+ ASSERT_THAT(v, IsListOfSize(5));
+
+ ASSERT_THAT(*v.listElems()[0], IsStringEq(""));
+
+ ASSERT_THAT(*v.listElems()[1], IsListOfSize(1));
+ ASSERT_THAT(*v.listElems()[1]->listElems()[0], IsStringEq("a"));
+
+ ASSERT_THAT(*v.listElems()[2], IsStringEq("b"));
+
+ ASSERT_THAT(*v.listElems()[3], IsListOfSize(1));
+ ASSERT_THAT(*v.listElems()[3]->listElems()[0], IsStringEq("c"));
+
+ ASSERT_THAT(*v.listElems()[4], IsStringEq(""));
+ }
+
+ TEST_F(PrimOpTest, split3) {
+ auto v = eval("builtins.split \"(a)|(c)\" \"abc\"");
+ ASSERT_THAT(v, IsListOfSize(5));
+
+ // First list element
+ ASSERT_THAT(*v.listElems()[0], IsStringEq(""));
+
+ // 2nd list element is a list [ "" null ]
+ ASSERT_THAT(*v.listElems()[1], IsListOfSize(2));
+ ASSERT_THAT(*v.listElems()[1]->listElems()[0], IsStringEq("a"));
+ ASSERT_THAT(*v.listElems()[1]->listElems()[1], IsNull());
+
+ // 3rd element
+ ASSERT_THAT(*v.listElems()[2], IsStringEq("b"));
+
+ // 4th element is a list: [ null "c" ]
+ ASSERT_THAT(*v.listElems()[3], IsListOfSize(2));
+ ASSERT_THAT(*v.listElems()[3]->listElems()[0], IsNull());
+ ASSERT_THAT(*v.listElems()[3]->listElems()[1], IsStringEq("c"));
+
+ // 5th element is the empty string
+ ASSERT_THAT(*v.listElems()[4], IsStringEq(""));
+ }
+
+ TEST_F(PrimOpTest, split4) {
+ auto v = eval("builtins.split \"([[:upper:]]+)\" \" FOO \"");
+ ASSERT_THAT(v, IsListOfSize(3));
+ auto first = v.listElems()[0];
+ auto second = v.listElems()[1];
+ auto third = v.listElems()[2];
+
+ ASSERT_THAT(*first, IsStringEq(" "));
+
+ ASSERT_THAT(*second, IsListOfSize(1));
+ ASSERT_THAT(*second->listElems()[0], IsStringEq("FOO"));
+
+ ASSERT_THAT(*third, IsStringEq(" "));
+ }
+
+ TEST_F(PrimOpTest, match1) {
+ auto v = eval("builtins.match \"ab\" \"abc\"");
+ ASSERT_THAT(v, IsNull());
+ }
+
+ TEST_F(PrimOpTest, match2) {
+ auto v = eval("builtins.match \"abc\" \"abc\"");
+ ASSERT_THAT(v, IsListOfSize(0));
+ }
+
+ TEST_F(PrimOpTest, match3) {
+ auto v = eval("builtins.match \"a(b)(c)\" \"abc\"");
+ ASSERT_THAT(v, IsListOfSize(2));
+ ASSERT_THAT(*v.listElems()[0], IsStringEq("b"));
+ ASSERT_THAT(*v.listElems()[1], IsStringEq("c"));
+ }
+
+ TEST_F(PrimOpTest, match4) {
+ auto v = eval("builtins.match \"[[:space:]]+([[:upper:]]+)[[:space:]]+\" \" FOO \"");
+ ASSERT_THAT(v, IsListOfSize(1));
+ ASSERT_THAT(*v.listElems()[0], IsStringEq("FOO"));
+ }
+
+ TEST_F(PrimOpTest, attrNames) {
+ auto v = eval("builtins.attrNames { x = 1; y = 2; z = 3; a = 2; }");
+ ASSERT_THAT(v, IsListOfSize(4));
+
+ // ensure that the list is sorted
+ const std::vector<std::string_view> expected { "a", "x", "y", "z" };
+ for (const auto [n, elem] : enumerate(v.listItems()))
+ ASSERT_THAT(*elem, IsStringEq(expected[n]));
+ }
+} /* namespace nix */
diff --git a/src/libexpr/tests/trivial.cc b/src/libexpr/tests/trivial.cc
new file mode 100644
index 000000000..8ce276e52
--- /dev/null
+++ b/src/libexpr/tests/trivial.cc
@@ -0,0 +1,196 @@
+#include "libexprtests.hh"
+
+namespace nix {
+ // Testing of trivial expressions
+ class TrivialExpressionTest : public LibExprTest {};
+
+ TEST_F(TrivialExpressionTest, true) {
+ auto v = eval("true");
+ ASSERT_THAT(v, IsTrue());
+ }
+
+ TEST_F(TrivialExpressionTest, false) {
+ auto v = eval("false");
+ ASSERT_THAT(v, IsFalse());
+ }
+
+ TEST_F(TrivialExpressionTest, null) {
+ auto v = eval("null");
+ ASSERT_THAT(v, IsNull());
+ }
+
+ TEST_F(TrivialExpressionTest, 1) {
+ auto v = eval("1");
+ ASSERT_THAT(v, IsIntEq(1));
+ }
+
+ TEST_F(TrivialExpressionTest, 1plus1) {
+ auto v = eval("1+1");
+ ASSERT_THAT(v, IsIntEq(2));
+ }
+
+ TEST_F(TrivialExpressionTest, minus1) {
+ auto v = eval("-1");
+ ASSERT_THAT(v, IsIntEq(-1));
+ }
+
+ TEST_F(TrivialExpressionTest, 1minus1) {
+ auto v = eval("1-1");
+ ASSERT_THAT(v, IsIntEq(0));
+ }
+
+ TEST_F(TrivialExpressionTest, lambdaAdd) {
+ auto v = eval("let add = a: b: a + b; in add 1 2");
+ ASSERT_THAT(v, IsIntEq(3));
+ }
+
+ TEST_F(TrivialExpressionTest, list) {
+ auto v = eval("[]");
+ ASSERT_THAT(v, IsListOfSize(0));
+ }
+
+ TEST_F(TrivialExpressionTest, attrs) {
+ auto v = eval("{}");
+ ASSERT_THAT(v, IsAttrsOfSize(0));
+ }
+
+ TEST_F(TrivialExpressionTest, float) {
+ auto v = eval("1.234");
+ ASSERT_THAT(v, IsFloatEq(1.234));
+ }
+
+ TEST_F(TrivialExpressionTest, updateAttrs) {
+ auto v = eval("{ a = 1; } // { b = 2; a = 3; }");
+ ASSERT_THAT(v, IsAttrsOfSize(2));
+ auto a = v.attrs->find(createSymbol("a"));
+ ASSERT_NE(a, nullptr);
+ ASSERT_THAT(*a->value, IsIntEq(3));
+
+ auto b = v.attrs->find(createSymbol("b"));
+ ASSERT_NE(b, nullptr);
+ ASSERT_THAT(*b->value, IsIntEq(2));
+ }
+
+ TEST_F(TrivialExpressionTest, hasAttrOpFalse) {
+ auto v = eval("{} ? a");
+ ASSERT_THAT(v, IsFalse());
+ }
+
+ TEST_F(TrivialExpressionTest, hasAttrOpTrue) {
+ auto v = eval("{ a = 123; } ? a");
+ ASSERT_THAT(v, IsTrue());
+ }
+
+ TEST_F(TrivialExpressionTest, withFound) {
+ auto v = eval("with { a = 23; }; a");
+ ASSERT_THAT(v, IsIntEq(23));
+ }
+
+ TEST_F(TrivialExpressionTest, withNotFound) {
+ ASSERT_THROW(eval("with {}; a"), Error);
+ }
+
+ TEST_F(TrivialExpressionTest, withOverride) {
+ auto v = eval("with { a = 23; }; with { a = 42; }; a");
+ ASSERT_THAT(v, IsIntEq(42));
+ }
+
+ TEST_F(TrivialExpressionTest, letOverWith) {
+ auto v = eval("let a = 23; in with { a = 1; }; a");
+ ASSERT_THAT(v, IsIntEq(23));
+ }
+
+ TEST_F(TrivialExpressionTest, multipleLet) {
+ auto v = eval("let a = 23; in let a = 42; in a");
+ ASSERT_THAT(v, IsIntEq(42));
+ }
+
+ TEST_F(TrivialExpressionTest, defaultFunctionArgs) {
+ auto v = eval("({ a ? 123 }: a) {}");
+ ASSERT_THAT(v, IsIntEq(123));
+ }
+
+ TEST_F(TrivialExpressionTest, defaultFunctionArgsOverride) {
+ auto v = eval("({ a ? 123 }: a) { a = 5; }");
+ ASSERT_THAT(v, IsIntEq(5));
+ }
+
+ TEST_F(TrivialExpressionTest, defaultFunctionArgsCaptureBack) {
+ auto v = eval("({ a ? 123 }@args: args) {}");
+ ASSERT_THAT(v, IsAttrsOfSize(0));
+ }
+
+ TEST_F(TrivialExpressionTest, defaultFunctionArgsCaptureFront) {
+ auto v = eval("(args@{ a ? 123 }: args) {}");
+ ASSERT_THAT(v, IsAttrsOfSize(0));
+ }
+
+ TEST_F(TrivialExpressionTest, assertThrows) {
+ ASSERT_THROW(eval("let x = arg: assert arg == 1; 123; in x 2"), Error);
+ }
+
+ TEST_F(TrivialExpressionTest, assertPassed) {
+ auto v = eval("let x = arg: assert arg == 1; 123; in x 1");
+ ASSERT_THAT(v, IsIntEq(123));
+ }
+
+ class AttrSetMergeTrvialExpressionTest :
+ public TrivialExpressionTest,
+ public testing::WithParamInterface<const char*>
+ {};
+
+ TEST_P(AttrSetMergeTrvialExpressionTest, attrsetMergeLazy) {
+ // Usually Nix rejects duplicate keys in an attrset but it does allow
+ // so if it is an attribute set that contains disjoint sets of keys.
+ // The below is equivalent to `{a.b = 1; a.c = 2; }`.
+ // The attribute set `a` will be a Thunk at first as the attribuets
+ // have to be merged (or otherwise computed) and that is done in a lazy
+ // manner.
+
+ auto expr = GetParam();
+ auto v = eval(expr);
+ ASSERT_THAT(v, IsAttrsOfSize(1));
+
+ auto a = v.attrs->find(createSymbol("a"));
+ ASSERT_NE(a, nullptr);
+
+ ASSERT_THAT(*a->value, IsThunk());
+ state.forceValue(*a->value, noPos);
+
+ ASSERT_THAT(*a->value, IsAttrsOfSize(2));
+
+ auto b = a->value->attrs->find(createSymbol("b"));
+ ASSERT_NE(b, nullptr);
+ ASSERT_THAT(*b->value, IsIntEq(1));
+
+ auto c = a->value->attrs->find(createSymbol("c"));
+ ASSERT_NE(c, nullptr);
+ ASSERT_THAT(*c->value, IsIntEq(2));
+ }
+
+ INSTANTIATE_TEST_SUITE_P(
+ attrsetMergeLazy,
+ AttrSetMergeTrvialExpressionTest,
+ testing::Values(
+ "{ a.b = 1; a.c = 2; }",
+ "{ a = { b = 1; }; a = { c = 2; }; }"
+ )
+ );
+
+ TEST_F(TrivialExpressionTest, functor) {
+ auto v = eval("{ __functor = self: arg: self.v + arg; v = 10; } 5");
+ ASSERT_THAT(v, IsIntEq(15));
+ }
+
+ TEST_F(TrivialExpressionTest, bindOr) {
+ auto v = eval("{ or = 1; }");
+ ASSERT_THAT(v, IsAttrsOfSize(1));
+ auto b = v.attrs->find(createSymbol("or"));
+ ASSERT_NE(b, nullptr);
+ ASSERT_THAT(*b->value, IsIntEq(1));
+ }
+
+ TEST_F(TrivialExpressionTest, orCantBeUsed) {
+ ASSERT_THROW(eval("let or = 1; in or"), Error);
+ }
+} /* namespace nix */
diff --git a/src/libexpr/value-to-json.cc b/src/libexpr/value-to-json.cc
index 517da4c01..4d63d8b49 100644
--- a/src/libexpr/value-to-json.cc
+++ b/src/libexpr/value-to-json.cc
@@ -10,7 +10,7 @@
namespace nix {
void printValueAsJSON(EvalState & state, bool strict,
- Value & v, const Pos & pos, JSONPlaceholder & out, PathSet & context)
+ Value & v, const PosIdx pos, JSONPlaceholder & out, PathSet & context, bool copyToStore)
{
checkInterrupt();
@@ -32,7 +32,10 @@ void printValueAsJSON(EvalState & state, bool strict,
break;
case nPath:
- out.write(state.copyPathToStore(context, v.path));
+ if (copyToStore)
+ out.write(state.copyPathToStore(context, v.path));
+ else
+ out.write(v.path);
break;
case nNull:
@@ -50,14 +53,14 @@ void printValueAsJSON(EvalState & state, bool strict,
auto obj(out.object());
StringSet names;
for (auto & j : *v.attrs)
- names.insert(j.name);
+ names.emplace(state.symbols[j.name]);
for (auto & j : names) {
Attr & a(*v.attrs->find(state.symbols.create(j)));
auto placeholder(obj.placeholder(j));
- printValueAsJSON(state, strict, *a.value, *a.pos, placeholder, context);
+ printValueAsJSON(state, strict, *a.value, a.pos, placeholder, context, copyToStore);
}
} else
- printValueAsJSON(state, strict, *i->value, *i->pos, out, context);
+ printValueAsJSON(state, strict, *i->value, i->pos, out, context, copyToStore);
break;
}
@@ -65,13 +68,13 @@ void printValueAsJSON(EvalState & state, bool strict,
auto list(out.list());
for (auto elem : v.listItems()) {
auto placeholder(list.placeholder());
- printValueAsJSON(state, strict, *elem, pos, placeholder, context);
+ printValueAsJSON(state, strict, *elem, pos, placeholder, context, copyToStore);
}
break;
}
case nExternal:
- v.external->printValueAsJSON(state, strict, out, context);
+ v.external->printValueAsJSON(state, strict, out, context, copyToStore);
break;
case nFloat:
@@ -82,23 +85,25 @@ void printValueAsJSON(EvalState & state, bool strict,
case nFunction:
auto e = TypeError({
.msg = hintfmt("cannot convert %1% to JSON", showType(v)),
- .errPos = v.determinePos(pos)
+ .errPos = state.positions[v.determinePos(pos)]
});
- throw e.addTrace(pos, hintfmt("message for the trace"));
+ e.addTrace(state.positions[pos], hintfmt("message for the trace"));
+ state.debugThrowLastTrace(e);
+ throw e;
}
}
void printValueAsJSON(EvalState & state, bool strict,
- Value & v, const Pos & pos, std::ostream & str, PathSet & context)
+ Value & v, const PosIdx pos, std::ostream & str, PathSet & context, bool copyToStore)
{
JSONPlaceholder out(str);
- printValueAsJSON(state, strict, v, pos, out, context);
+ printValueAsJSON(state, strict, v, pos, out, context, copyToStore);
}
void ExternalValueBase::printValueAsJSON(EvalState & state, bool strict,
- JSONPlaceholder & out, PathSet & context) const
+ JSONPlaceholder & out, PathSet & context, bool copyToStore) const
{
- throw TypeError("cannot convert %1% to JSON", showType());
+ state.debugThrowLastTrace(TypeError("cannot convert %1% to JSON", showType()));
}
diff --git a/src/libexpr/value-to-json.hh b/src/libexpr/value-to-json.hh
index c2f797b29..7ddc8a5b1 100644
--- a/src/libexpr/value-to-json.hh
+++ b/src/libexpr/value-to-json.hh
@@ -11,9 +11,9 @@ namespace nix {
class JSONPlaceholder;
void printValueAsJSON(EvalState & state, bool strict,
- Value & v, const Pos & pos, JSONPlaceholder & out, PathSet & context);
+ Value & v, const PosIdx pos, JSONPlaceholder & out, PathSet & context, bool copyToStore = true);
void printValueAsJSON(EvalState & state, bool strict,
- Value & v, const Pos & pos, std::ostream & str, PathSet & context);
+ Value & v, const PosIdx pos, std::ostream & str, PathSet & context, bool copyToStore = true);
}
diff --git a/src/libexpr/value-to-xml.cc b/src/libexpr/value-to-xml.cc
index afeaf5694..7c3bf9492 100644
--- a/src/libexpr/value-to-xml.cc
+++ b/src/libexpr/value-to-xml.cc
@@ -19,10 +19,10 @@ static XMLAttrs singletonAttrs(const std::string & name, const std::string & val
static void printValueAsXML(EvalState & state, bool strict, bool location,
Value & v, XMLWriter & doc, PathSet & context, PathSet & drvsSeen,
- const Pos & pos);
+ const PosIdx pos);
-static void posToXML(XMLAttrs & xmlAttrs, const Pos & pos)
+static void posToXML(EvalState & state, XMLAttrs & xmlAttrs, const Pos & pos)
{
xmlAttrs["path"] = pos.file;
xmlAttrs["line"] = (format("%1%") % pos.line).str();
@@ -36,25 +36,25 @@ static void showAttrs(EvalState & state, bool strict, bool location,
StringSet names;
for (auto & i : attrs)
- names.insert(i.name);
+ names.emplace(state.symbols[i.name]);
for (auto & i : names) {
Attr & a(*attrs.find(state.symbols.create(i)));
XMLAttrs xmlAttrs;
xmlAttrs["name"] = i;
- if (location && a.pos != ptr(&noPos)) posToXML(xmlAttrs, *a.pos);
+ if (location && a.pos) posToXML(state, xmlAttrs, state.positions[a.pos]);
XMLOpenElement _(doc, "attr", xmlAttrs);
printValueAsXML(state, strict, location,
- *a.value, doc, context, drvsSeen, *a.pos);
+ *a.value, doc, context, drvsSeen, a.pos);
}
}
static void printValueAsXML(EvalState & state, bool strict, bool location,
Value & v, XMLWriter & doc, PathSet & context, PathSet & drvsSeen,
- const Pos & pos)
+ const PosIdx pos)
{
checkInterrupt();
@@ -93,14 +93,14 @@ static void printValueAsXML(EvalState & state, bool strict, bool location,
Path drvPath;
a = v.attrs->find(state.sDrvPath);
if (a != v.attrs->end()) {
- if (strict) state.forceValue(*a->value, *a->pos);
+ if (strict) state.forceValue(*a->value, a->pos);
if (a->value->type() == nString)
xmlAttrs["drvPath"] = drvPath = a->value->string.s;
}
a = v.attrs->find(state.sOutPath);
if (a != v.attrs->end()) {
- if (strict) state.forceValue(*a->value, *a->pos);
+ if (strict) state.forceValue(*a->value, a->pos);
if (a->value->type() == nString)
xmlAttrs["outPath"] = a->value->string.s;
}
@@ -134,18 +134,18 @@ static void printValueAsXML(EvalState & state, bool strict, bool location,
break;
}
XMLAttrs xmlAttrs;
- if (location) posToXML(xmlAttrs, v.lambda.fun->pos);
+ if (location) posToXML(state, xmlAttrs, state.positions[v.lambda.fun->pos]);
XMLOpenElement _(doc, "function", xmlAttrs);
if (v.lambda.fun->hasFormals()) {
XMLAttrs attrs;
- if (!v.lambda.fun->arg.empty()) attrs["name"] = v.lambda.fun->arg;
+ if (v.lambda.fun->arg) attrs["name"] = state.symbols[v.lambda.fun->arg];
if (v.lambda.fun->formals->ellipsis) attrs["ellipsis"] = "1";
XMLOpenElement _(doc, "attrspat", attrs);
- for (auto & i : v.lambda.fun->formals->lexicographicOrder())
- doc.writeEmptyElement("attr", singletonAttrs("name", i.name));
+ for (auto & i : v.lambda.fun->formals->lexicographicOrder(state.symbols))
+ doc.writeEmptyElement("attr", singletonAttrs("name", state.symbols[i.name]));
} else
- doc.writeEmptyElement("varpat", singletonAttrs("name", v.lambda.fun->arg));
+ doc.writeEmptyElement("varpat", singletonAttrs("name", state.symbols[v.lambda.fun->arg]));
break;
}
@@ -166,14 +166,14 @@ static void printValueAsXML(EvalState & state, bool strict, bool location,
void ExternalValueBase::printValueAsXML(EvalState & state, bool strict,
bool location, XMLWriter & doc, PathSet & context, PathSet & drvsSeen,
- const Pos & pos) const
+ const PosIdx pos) const
{
doc.writeEmptyElement("unevaluated");
}
void printValueAsXML(EvalState & state, bool strict, bool location,
- Value & v, std::ostream & out, PathSet & context, const Pos & pos)
+ Value & v, std::ostream & out, PathSet & context, const PosIdx pos)
{
XMLWriter doc(true, out);
XMLOpenElement root(doc, "expr");
diff --git a/src/libexpr/value-to-xml.hh b/src/libexpr/value-to-xml.hh
index cc778a2cb..506f32b6b 100644
--- a/src/libexpr/value-to-xml.hh
+++ b/src/libexpr/value-to-xml.hh
@@ -9,6 +9,6 @@
namespace nix {
void printValueAsXML(EvalState & state, bool strict, bool location,
- Value & v, std::ostream & out, PathSet & context, const Pos & pos);
+ Value & v, std::ostream & out, PathSet & context, const PosIdx pos);
}
diff --git a/src/libexpr/value.hh b/src/libexpr/value.hh
index 3fdff71a5..590ba7783 100644
--- a/src/libexpr/value.hh
+++ b/src/libexpr/value.hh
@@ -56,7 +56,10 @@ struct Expr;
struct ExprLambda;
struct PrimOp;
class Symbol;
+class PosIdx;
struct Pos;
+class StorePath;
+class Store;
class EvalState;
class XMLWriter;
class JSONPlaceholder;
@@ -64,6 +67,8 @@ class JSONPlaceholder;
typedef int64_t NixInt;
typedef double NixFloat;
+typedef std::pair<StorePath, std::string> NixStringContextElem;
+typedef std::vector<NixStringContextElem> NixStringContext;
/* External values must descend from ExternalValueBase, so that
* type-agnostic nix functions (e.g. showType) can be implemented
@@ -94,12 +99,12 @@ class ExternalValueBase
/* Print the value as JSON. Defaults to unconvertable, i.e. throws an error */
virtual void printValueAsJSON(EvalState & state, bool strict,
- JSONPlaceholder & out, PathSet & context) const;
+ JSONPlaceholder & out, PathSet & context, bool copyToStore = true) const;
/* Print the value as XML. Defaults to unevaluated */
virtual void printValueAsXML(EvalState & state, bool strict, bool location,
XMLWriter & doc, PathSet & context, PathSet & drvsSeen,
- const Pos & pos) const;
+ const PosIdx pos) const;
virtual ~ExternalValueBase()
{
@@ -114,11 +119,14 @@ struct Value
private:
InternalType internalType;
-friend std::string showType(const Value & v);
-friend void printValue(std::ostream & str, std::set<const Value *> & active, const Value & v);
+ friend std::string showType(const Value & v);
+
+ void print(const SymbolTable & symbols, std::ostream & str, std::set<const void *> * seen) const;
public:
+ void print(const SymbolTable & symbols, std::ostream & str, bool showRepeated = false) const;
+
// Functions needed to distinguish the type
// These should be removed eventually, by putting the functionality that's
// needed by callers into methods of this type
@@ -243,11 +251,6 @@ public:
void mkStringMove(const char * s, const PathSet & context);
- inline void mkString(const Symbol & s)
- {
- mkString(((const std::string &) s).c_str());
- }
-
inline void mkPath(const char * s)
{
clearValue();
@@ -361,14 +364,14 @@ public:
return internalType == tList1 ? 1 : internalType == tList2 ? 2 : bigList.size;
}
- Pos determinePos(const Pos & pos) const;
+ PosIdx determinePos(const PosIdx pos) const;
/* Check whether forcing this value requires a trivial amount of
computation. In particular, function applications are
non-trivial. */
bool isTrivial() const;
- std::vector<std::pair<Path, std::string>> getContext();
+ NixStringContext getContext(const Store &);
auto listItems()
{
@@ -401,9 +404,9 @@ public:
#if HAVE_BOEHMGC
-typedef std::vector<Value *, traceable_allocator<Value *> > ValueVector;
-typedef std::map<Symbol, Value *, std::less<Symbol>, traceable_allocator<std::pair<const Symbol, Value *> > > ValueMap;
-typedef std::map<Symbol, ValueVector, std::less<Symbol>, traceable_allocator<std::pair<const Symbol, ValueVector> > > ValueVectorMap;
+typedef std::vector<Value *, traceable_allocator<Value *>> ValueVector;
+typedef std::map<Symbol, Value *, std::less<Symbol>, traceable_allocator<std::pair<const Symbol, Value *>>> ValueMap;
+typedef std::map<Symbol, ValueVector, std::less<Symbol>, traceable_allocator<std::pair<const Symbol, ValueVector>>> ValueVectorMap;
#else
typedef std::vector<Value *> ValueVector;
typedef std::map<Symbol, Value *> ValueMap;