1
1
Fork 0
mirror of https://github.com/NixOS/nix.git synced 2025-12-09 18:41:03 +01:00

Introduce AttrPath type

This is basically an alias for std::vector<Symbol>.
This commit is contained in:
Eelco Dolstra 2025-12-05 13:41:59 +01:00
parent 294e68a3f6
commit 20fc54c00d
9 changed files with 64 additions and 55 deletions

View file

@ -171,7 +171,7 @@ std::vector<ref<eval_cache::AttrCursor>> InstallableFlake::getCursors(EvalState
for (auto & attrPath : attrPaths) { for (auto & attrPath : attrPaths) {
debug("trying flake output attribute '%s'", attrPath); debug("trying flake output attribute '%s'", attrPath);
auto attr = root->findAlongAttrPath(parseAttrPath(state, attrPath)); auto attr = root->findAlongAttrPath(AttrPath::parse(state, attrPath));
if (attr) { if (attr) {
res.push_back(ref(*attr)); res.push_back(ref(*attr));
} else { } else {

View file

@ -355,9 +355,9 @@ void completeFlakeRefWithFragment(
attrPathPrefixes.push_back(""); attrPathPrefixes.push_back("");
for (auto & attrPathPrefixS : attrPathPrefixes) { for (auto & attrPathPrefixS : attrPathPrefixes) {
auto attrPathPrefix = parseAttrPath(*evalState, attrPathPrefixS); auto attrPathPrefix = AttrPath::parse(*evalState, attrPathPrefixS);
auto attrPathS = attrPathPrefixS + std::string(fragment); auto attrPathS = attrPathPrefixS + std::string(fragment);
auto attrPath = parseAttrPath(*evalState, attrPathS); auto attrPath = AttrPath::parse(*evalState, attrPathS);
std::string lastAttr; std::string lastAttr;
if (!attrPath.empty() && !hasSuffix(attrPathS, ".")) { if (!attrPath.empty() && !hasSuffix(attrPathS, ".")) {
@ -375,9 +375,7 @@ void completeFlakeRefWithFragment(
/* Strip the attrpath prefix. */ /* Strip the attrpath prefix. */
attrPath2.erase(attrPath2.begin(), attrPath2.begin() + attrPathPrefix.size()); attrPath2.erase(attrPath2.begin(), attrPath2.begin() + attrPathPrefix.size());
// FIXME: handle names with dots // FIXME: handle names with dots
completions.add( completions.add(flakeRefS + "#" + prefixRoot + attrPath2.to_string(*evalState));
flakeRefS + "#" + prefixRoot
+ concatStringsSep(".", evalState->symbols.resolve(attrPath2)));
} }
} }
} }
@ -386,7 +384,7 @@ void completeFlakeRefWithFragment(
attrpaths. */ attrpaths. */
if (fragment.empty()) { if (fragment.empty()) {
for (auto & attrPath : defaultFlakeAttrPaths) { for (auto & attrPath : defaultFlakeAttrPaths) {
auto attr = root->findAlongAttrPath(parseAttrPath(*evalState, attrPath)); auto attr = root->findAlongAttrPath(AttrPath::parse(*evalState, attrPath));
if (!attr) if (!attr)
continue; continue;
completions.add(flakeRefS + "#" + prefixRoot); completions.add(flakeRefS + "#" + prefixRoot);

View file

@ -1,5 +1,6 @@
#include "nix/expr/attr-path.hh" #include "nix/expr/attr-path.hh"
#include "nix/expr/eval-inline.hh" #include "nix/expr/eval-inline.hh"
#include "nix/util/strings-inline.hh"
namespace nix { namespace nix {
@ -30,14 +31,24 @@ static Strings parseAttrPath(std::string_view s)
return res; return res;
} }
std::vector<Symbol> parseAttrPath(EvalState & state, std::string_view s) AttrPath AttrPath::parse(EvalState & state, std::string_view s)
{ {
std::vector<Symbol> res; AttrPath res;
for (auto & a : parseAttrPath(s)) for (auto & a : parseAttrPath(s))
res.push_back(state.symbols.create(a)); res.push_back(state.symbols.create(a));
return res; return res;
} }
std::string AttrPath::to_string(EvalState & state) const
{
return dropEmptyInitThenConcatStringsSep(".", state.symbols.resolve({*this}));
}
std::vector<SymbolStr> AttrPath::resolve(EvalState & state) const
{
return state.symbols.resolve({*this});
}
std::pair<Value *, PosIdx> std::pair<Value *, PosIdx>
findAlongAttrPath(EvalState & state, const std::string & attrPath, Bindings & autoArgs, Value & vIn) findAlongAttrPath(EvalState & state, const std::string & attrPath, Bindings & autoArgs, Value & vIn)
{ {

View file

@ -364,7 +364,7 @@ void AttrCursor::fetchCachedValue()
throw CachedEvalError(parent->first, parent->second); throw CachedEvalError(parent->first, parent->second);
} }
std::vector<Symbol> AttrCursor::getAttrPath() const AttrPath AttrCursor::getAttrPath() const
{ {
if (parent) { if (parent) {
auto attrPath = parent->first->getAttrPath(); auto attrPath = parent->first->getAttrPath();
@ -374,7 +374,7 @@ std::vector<Symbol> AttrCursor::getAttrPath() const
return {}; return {};
} }
std::vector<Symbol> AttrCursor::getAttrPath(Symbol name) const AttrPath AttrCursor::getAttrPath(Symbol name) const
{ {
auto attrPath = getAttrPath(); auto attrPath = getAttrPath();
attrPath.push_back(name); attrPath.push_back(name);
@ -383,12 +383,12 @@ std::vector<Symbol> AttrCursor::getAttrPath(Symbol name) const
std::string AttrCursor::getAttrPathStr() const std::string AttrCursor::getAttrPathStr() const
{ {
return dropEmptyInitThenConcatStringsSep(".", root->state.symbols.resolve(getAttrPath())); return getAttrPath().to_string(root->state);
} }
std::string AttrCursor::getAttrPathStr(Symbol name) const std::string AttrCursor::getAttrPathStr(Symbol name) const
{ {
return dropEmptyInitThenConcatStringsSep(".", root->state.symbols.resolve(getAttrPath(name))); return getAttrPath(name).to_string(root->state);
} }
Value & AttrCursor::forceValue() Value & AttrCursor::forceValue()
@ -511,7 +511,7 @@ ref<AttrCursor> AttrCursor::getAttr(std::string_view name)
return getAttr(root->state.symbols.create(name)); return getAttr(root->state.symbols.create(name));
} }
OrSuggestions<ref<AttrCursor>> AttrCursor::findAlongAttrPath(const std::vector<Symbol> & attrPath) OrSuggestions<ref<AttrCursor>> AttrCursor::findAlongAttrPath(const AttrPath & attrPath)
{ {
auto res = shared_from_this(); auto res = shared_from_this();
for (auto & attr : attrPath) { for (auto & attr : attrPath) {

View file

@ -19,6 +19,15 @@ findAlongAttrPath(EvalState & state, const std::string & attrPath, Bindings & au
*/ */
std::pair<SourcePath, uint32_t> findPackageFilename(EvalState & state, Value & v, std::string what); std::pair<SourcePath, uint32_t> findPackageFilename(EvalState & state, Value & v, std::string what);
std::vector<Symbol> parseAttrPath(EvalState & state, std::string_view s); struct AttrPath : std::vector<Symbol>
{
using std::vector<Symbol>::vector;
static AttrPath parse(EvalState & state, std::string_view s);
std::string to_string(EvalState & state) const;
std::vector<SymbolStr> resolve(EvalState & state) const;
};
} // namespace nix } // namespace nix

View file

@ -4,6 +4,7 @@
#include "nix/util/sync.hh" #include "nix/util/sync.hh"
#include "nix/util/hash.hh" #include "nix/util/hash.hh"
#include "nix/expr/eval.hh" #include "nix/expr/eval.hh"
#include "nix/expr/attr-path.hh"
#include <functional> #include <functional>
#include <variant> #include <variant>
@ -124,9 +125,9 @@ public:
Value * value = nullptr, Value * value = nullptr,
std::optional<std::pair<AttrId, AttrValue>> && cachedValue = {}); std::optional<std::pair<AttrId, AttrValue>> && cachedValue = {});
std::vector<Symbol> getAttrPath() const; AttrPath getAttrPath() const;
std::vector<Symbol> getAttrPath(Symbol name) const; AttrPath getAttrPath(Symbol name) const;
std::string getAttrPathStr() const; std::string getAttrPathStr() const;
@ -146,7 +147,7 @@ public:
* Get an attribute along a chain of attrsets. Note that this does * Get an attribute along a chain of attrsets. Note that this does
* not auto-call functors or functions. * not auto-call functors or functions.
*/ */
OrSuggestions<ref<AttrCursor>> findAlongAttrPath(const std::vector<Symbol> & attrPath); OrSuggestions<ref<AttrCursor>> findAlongAttrPath(const AttrPath & attrPath);
std::string getString(); std::string getString();

View file

@ -290,7 +290,7 @@ public:
return Symbol(*symbols.insert(SymbolStr::Key{store, s, buffer}).first); return Symbol(*symbols.insert(SymbolStr::Key{store, s, buffer}).first);
} }
std::vector<SymbolStr> resolve(const std::vector<Symbol> & symbols) const std::vector<SymbolStr> resolve(const std::span<const Symbol> & symbols) const
{ {
std::vector<SymbolStr> result; std::vector<SymbolStr> result;
result.reserve(symbols.size()); result.reserve(symbols.size());

View file

@ -418,7 +418,7 @@ struct CmdFlakeCheck : FlakeCommand
return std::nullopt; return std::nullopt;
}; };
std::map<DerivedPath, std::vector<AttrSelectionPath>> attrPathsByDrv; std::map<DerivedPath, std::vector<AttrPath>> attrPathsByDrv;
auto checkApp = [&](const std::string & attrPath, Value & v, const PosIdx pos) { auto checkApp = [&](const std::string & attrPath, Value & v, const PosIdx pos) {
try { try {
@ -618,10 +618,7 @@ struct CmdFlakeCheck : FlakeCommand
}; };
// Build and store the attribute path for error reporting // Build and store the attribute path for error reporting
AttrSelectionPath attrPath; AttrPath attrPath{state->symbols.create(name), attr.name, attr2.name};
attrPath.push_back(AttrName(state->symbols.create(name)));
attrPath.push_back(AttrName(attr.name));
attrPath.push_back(AttrName(attr2.name));
attrPathsByDrv[path].push_back(std::move(attrPath)); attrPathsByDrv[path].push_back(std::move(attrPath));
} }
} }
@ -820,10 +817,9 @@ struct CmdFlakeCheck : FlakeCommand
auto it = attrPathsByDrv.find(result.path); auto it = attrPathsByDrv.find(result.path);
if (it != attrPathsByDrv.end() && !it->second.empty()) { if (it != attrPathsByDrv.end() && !it->second.empty()) {
for (auto & attrPath : it->second) { for (auto & attrPath : it->second) {
auto attrPathStr = showAttrSelectionPath(state->symbols, attrPath);
reportError(Error( reportError(Error(
"failed to build attribute '%s', build of '%s' failed: %s", "failed to build attribute '%s', build of '%s' failed: %s",
attrPathStr, attrPath.to_string(*state),
result.path.to_string(*store), result.path.to_string(*store),
failure->errorMsg)); failure->errorMsg));
} }
@ -1172,7 +1168,7 @@ struct CmdFlakeShow : FlakeCommand, MixJSON
auto flake = make_ref<LockedFlake>(lockFlake()); auto flake = make_ref<LockedFlake>(lockFlake());
auto localSystem = std::string(settings.thisSystem.get()); auto localSystem = std::string(settings.thisSystem.get());
std::function<bool(eval_cache::AttrCursor & visitor, const std::vector<Symbol> & attrPath, const Symbol & attr)> std::function<bool(eval_cache::AttrCursor & visitor, const AttrPath & attrPath, const Symbol & attr)>
hasContent; hasContent;
// For frameworks it's important that structures are as lazy as possible // For frameworks it's important that structures are as lazy as possible
@ -1181,11 +1177,10 @@ struct CmdFlakeShow : FlakeCommand, MixJSON
// to emit more attributes than strictly (sic) necessary. // to emit more attributes than strictly (sic) necessary.
// However, these attributes with empty values are not useful to the user // However, these attributes with empty values are not useful to the user
// so we omit them. // so we omit them.
hasContent = hasContent = [&](eval_cache::AttrCursor & visitor, const AttrPath & attrPath, const Symbol & attr) -> bool {
[&](eval_cache::AttrCursor & visitor, const std::vector<Symbol> & attrPath, const Symbol & attr) -> bool {
auto attrPath2(attrPath); auto attrPath2(attrPath);
attrPath2.push_back(attr); attrPath2.push_back(attr);
auto attrPathS = state->symbols.resolve(attrPath2); auto attrPathS = attrPath2.resolve(*state);
const auto & attrName = state->symbols[attr]; const auto & attrName = state->symbols[attr];
auto visitor2 = visitor.getAttr(attrName); auto visitor2 = visitor.getAttr(attrName);
@ -1225,20 +1220,20 @@ struct CmdFlakeShow : FlakeCommand, MixJSON
std::function<nlohmann::json( std::function<nlohmann::json(
eval_cache::AttrCursor & visitor, eval_cache::AttrCursor & visitor,
const std::vector<Symbol> & attrPath, const AttrPath & attrPath,
const std::string & headerPrefix, const std::string & headerPrefix,
const std::string & nextPrefix)> const std::string & nextPrefix)>
visit; visit;
visit = [&](eval_cache::AttrCursor & visitor, visit = [&](eval_cache::AttrCursor & visitor,
const std::vector<Symbol> & attrPath, const AttrPath & attrPath,
const std::string & headerPrefix, const std::string & headerPrefix,
const std::string & nextPrefix) -> nlohmann::json { const std::string & nextPrefix) -> nlohmann::json {
auto j = nlohmann::json::object(); auto j = nlohmann::json::object();
auto attrPathS = state->symbols.resolve(attrPath); auto attrPathS = attrPath.resolve(*state);
Activity act(*logger, lvlInfo, actUnknown, fmt("evaluating '%s'", concatStringsSep(".", attrPathS))); Activity act(*logger, lvlInfo, actUnknown, fmt("evaluating '%s'", attrPath.to_string(*state)));
try { try {
auto recurse = [&]() { auto recurse = [&]() {
@ -1317,8 +1312,7 @@ struct CmdFlakeShow : FlakeCommand, MixJSON
fmt("%s " ANSI_WARNING "omitted" ANSI_NORMAL " (use '--all-systems' to show)", fmt("%s " ANSI_WARNING "omitted" ANSI_NORMAL " (use '--all-systems' to show)",
headerPrefix)); headerPrefix));
else { else {
logger->warn( logger->warn(fmt("%s omitted (use '--all-systems' to show)", attrPath.to_string(*state)));
fmt("%s omitted (use '--all-systems' to show)", concatStringsSep(".", attrPathS)));
} }
} else { } else {
try { try {
@ -1335,8 +1329,7 @@ struct CmdFlakeShow : FlakeCommand, MixJSON
headerPrefix)); headerPrefix));
} else { } else {
logger->warn( logger->warn(
fmt("%s omitted due to use of import from derivation", fmt("%s omitted due to use of import from derivation", attrPath.to_string(*state)));
concatStringsSep(".", attrPathS)));
} }
} }
} }
@ -1354,8 +1347,8 @@ struct CmdFlakeShow : FlakeCommand, MixJSON
fmt("%s " ANSI_WARNING "omitted due to use of import from derivation" ANSI_NORMAL, fmt("%s " ANSI_WARNING "omitted due to use of import from derivation" ANSI_NORMAL,
headerPrefix)); headerPrefix));
} else { } else {
logger->warn(fmt( logger->warn(
"%s omitted due to use of import from derivation", concatStringsSep(".", attrPathS))); fmt("%s omitted due to use of import from derivation", attrPath.to_string(*state)));
} }
} }
} }
@ -1368,7 +1361,7 @@ struct CmdFlakeShow : FlakeCommand, MixJSON
logger->cout(fmt( logger->cout(fmt(
"%s " ANSI_WARNING "omitted" ANSI_NORMAL " (use '--legacy' to show)", headerPrefix)); "%s " ANSI_WARNING "omitted" ANSI_NORMAL " (use '--legacy' to show)", headerPrefix));
else { else {
logger->warn(fmt("%s omitted (use '--legacy' to show)", concatStringsSep(".", attrPathS))); logger->warn(fmt("%s omitted (use '--legacy' to show)", attrPath.to_string(*state)));
} }
} else if (!showAllSystems && std::string(attrPathS[1]) != localSystem) { } else if (!showAllSystems && std::string(attrPathS[1]) != localSystem) {
if (!json) if (!json)
@ -1376,8 +1369,7 @@ struct CmdFlakeShow : FlakeCommand, MixJSON
fmt("%s " ANSI_WARNING "omitted" ANSI_NORMAL " (use '--all-systems' to show)", fmt("%s " ANSI_WARNING "omitted" ANSI_NORMAL " (use '--all-systems' to show)",
headerPrefix)); headerPrefix));
else { else {
logger->warn( logger->warn(fmt("%s omitted (use '--all-systems' to show)", attrPath.to_string(*state)));
fmt("%s omitted (use '--all-systems' to show)", concatStringsSep(".", attrPathS)));
} }
} else { } else {
try { try {
@ -1393,8 +1385,7 @@ struct CmdFlakeShow : FlakeCommand, MixJSON
headerPrefix)); headerPrefix));
} else { } else {
logger->warn( logger->warn(
fmt("%s omitted due to use of import from derivation", fmt("%s omitted due to use of import from derivation", attrPath.to_string(*state)));
concatStringsSep(".", attrPathS)));
} }
} }
} }

View file

@ -90,13 +90,13 @@ struct CmdSearch : InstallableValueCommand, MixJSON
uint64_t results = 0; uint64_t results = 0;
std::function<void(eval_cache::AttrCursor & cursor, const std::vector<Symbol> & attrPath, bool initialRecurse)> std::function<void(eval_cache::AttrCursor & cursor, const AttrPath & attrPath, bool initialRecurse)> visit;
visit;
visit = [&](eval_cache::AttrCursor & cursor, const std::vector<Symbol> & attrPath, bool initialRecurse) { visit = [&](eval_cache::AttrCursor & cursor, const AttrPath & attrPath, bool initialRecurse) {
auto attrPathS = state->symbols.resolve(attrPath); auto attrPathS = state->symbols.resolve({attrPath});
auto attrPathStr = attrPath.to_string(*state);
Activity act(*logger, lvlInfo, actUnknown, fmt("evaluating '%s'", concatStringsSep(".", attrPathS))); Activity act(*logger, lvlInfo, actUnknown, fmt("evaluating '%s'", attrPathStr));
try { try {
auto recurse = [&]() { auto recurse = [&]() {
for (const auto & attr : cursor.getAttrs()) { for (const auto & attr : cursor.getAttrs()) {
@ -114,7 +114,6 @@ struct CmdSearch : InstallableValueCommand, MixJSON
auto aDescription = aMeta ? aMeta->maybeGetAttr(state->s.description) : nullptr; auto aDescription = aMeta ? aMeta->maybeGetAttr(state->s.description) : nullptr;
auto description = aDescription ? aDescription->getString() : ""; auto description = aDescription ? aDescription->getString() : "";
std::replace(description.begin(), description.end(), '\n', ' '); std::replace(description.begin(), description.end(), '\n', ' ');
auto attrPath2 = concatStringsSep(".", attrPathS);
std::vector<std::smatch> attrPathMatches; std::vector<std::smatch> attrPathMatches;
std::vector<std::smatch> descriptionMatches; std::vector<std::smatch> descriptionMatches;
@ -122,7 +121,7 @@ struct CmdSearch : InstallableValueCommand, MixJSON
bool found = false; bool found = false;
for (auto & regex : excludeRegexes) { for (auto & regex : excludeRegexes) {
if (std::regex_search(attrPath2, regex) || std::regex_search(name.name, regex) if (std::regex_search(attrPathStr, regex) || std::regex_search(name.name, regex)
|| std::regex_search(description, regex)) || std::regex_search(description, regex))
return; return;
} }
@ -137,7 +136,7 @@ struct CmdSearch : InstallableValueCommand, MixJSON
} }
}; };
addAll(std::sregex_iterator(attrPath2.begin(), attrPath2.end(), regex), attrPathMatches); addAll(std::sregex_iterator(attrPathStr.begin(), attrPathStr.end(), regex), attrPathMatches);
addAll(std::sregex_iterator(name.name.begin(), name.name.end(), regex), nameMatches); addAll(std::sregex_iterator(name.name.begin(), name.name.end(), regex), nameMatches);
addAll(std::sregex_iterator(description.begin(), description.end(), regex), descriptionMatches); addAll(std::sregex_iterator(description.begin(), description.end(), regex), descriptionMatches);
@ -148,7 +147,7 @@ struct CmdSearch : InstallableValueCommand, MixJSON
if (found) { if (found) {
results++; results++;
if (json) { if (json) {
(*jsonOut)[attrPath2] = { (*jsonOut)[attrPathStr] = {
{"pname", name.name}, {"pname", name.name},
{"version", name.version}, {"version", name.version},
{"description", description}, {"description", description},
@ -158,7 +157,7 @@ struct CmdSearch : InstallableValueCommand, MixJSON
logger->cout(""); logger->cout("");
logger->cout( logger->cout(
"* %s%s", "* %s%s",
wrap("\e[0;1m", hiliteMatches(attrPath2, attrPathMatches, ANSI_GREEN, "\e[0;1m")), wrap("\e[0;1m", hiliteMatches(attrPathStr, attrPathMatches, ANSI_GREEN, "\e[0;1m")),
optionalBracket(" (", name.version, ")")); optionalBracket(" (", name.version, ")"));
if (description != "") if (description != "")
logger->cout( logger->cout(