nix-super/src/libexpr/value-to-json.cc

109 lines
2.9 KiB
C++
Raw Normal View History

2013-11-19 01:33:06 +02:00
#include "value-to-json.hh"
#include "json.hh"
2013-11-19 01:03:11 +02:00
#include "eval-inline.hh"
#include "util.hh"
#include <cstdlib>
#include <iomanip>
2013-11-19 01:03:11 +02:00
namespace nix {
void printValueAsJSON(EvalState & state, bool strict,
Value & v, const PosIdx pos, JSONPlaceholder & out, PathSet & context)
2013-11-19 01:03:11 +02:00
{
checkInterrupt();
if (strict) state.forceValue(v, pos);
2013-11-19 01:03:11 +02:00
switch (v.type()) {
2013-11-19 01:03:11 +02:00
case nInt:
out.write(v.integer);
2013-11-19 01:03:11 +02:00
break;
case nBool:
out.write(v.boolean);
2013-11-19 01:03:11 +02:00
break;
case nString:
2013-11-19 01:03:11 +02:00
copyContext(v, context);
out.write(v.string.s);
2013-11-19 01:03:11 +02:00
break;
case nPath:
out.write(state.copyPathToStore(context, v.path));
2013-11-19 01:03:11 +02:00
break;
case nNull:
out.write(nullptr);
2013-11-19 01:03:11 +02:00
break;
case nAttrs: {
auto maybeString = state.tryAttrsToString(pos, v, context, false, false);
2019-10-27 11:15:51 +02:00
if (maybeString) {
out.write(*maybeString);
break;
}
auto i = v.attrs->find(state.sOutPath);
2013-11-19 01:03:11 +02:00
if (i == v.attrs->end()) {
auto obj(out.object());
2013-11-19 01:03:11 +02:00
StringSet names;
2015-07-17 20:24:28 +03:00
for (auto & j : *v.attrs)
names.emplace(state.symbols[j.name]);
2015-07-17 20:24:28 +03:00
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);
2013-11-19 01:03:11 +02:00
}
} else
printValueAsJSON(state, strict, *i->value, i->pos, out, context);
2013-11-19 01:03:11 +02:00
break;
}
case nList: {
auto list(out.list());
for (auto elem : v.listItems()) {
auto placeholder(list.placeholder());
printValueAsJSON(state, strict, *elem, pos, placeholder, context);
2013-11-19 01:03:11 +02:00
}
break;
}
case nExternal:
v.external->printValueAsJSON(state, strict, out, context);
break;
case nFloat:
out.write(v.fpoint);
break;
case nThunk:
case nFunction:
auto e = TypeError({
.msg = hintfmt("cannot convert %1% to JSON", showType(v)),
.errPos = state.positions[v.determinePos(pos)]
});
e.addTrace(state.positions[pos], hintfmt("message for the trace"));
2022-05-06 17:47:21 +03:00
state.debugThrowLastTrace(e);
throw e;
2013-11-19 01:03:11 +02:00
}
}
void printValueAsJSON(EvalState & state, bool strict,
Value & v, const PosIdx pos, std::ostream & str, PathSet & context)
{
JSONPlaceholder out(str);
printValueAsJSON(state, strict, v, pos, out, context);
}
2013-11-19 01:03:11 +02:00
void ExternalValueBase::printValueAsJSON(EvalState & state, bool strict,
JSONPlaceholder & out, PathSet & context) const
{
auto e = TypeError("cannot convert %1% to JSON", showType());
2022-05-06 17:47:21 +03:00
state.debugThrowLastTrace(e);
}
2013-11-19 01:03:11 +02:00
}