20namespace utf8 = fe::utf8;
23#define PBQP_JSON_KEY(m) \
28#define PBQP_JSON_VAL(m) \
29 m(V_str, "<string>") \
30 m(V_int, "<integer>") \
31 m(V_num, "<number>") \
33#define PBQP_JSON_TOK(m) \
34 m(EoF, "<end of file>") \
54 Tok(fe::Loc loc, Tag tag)
57 Tok(fe::Loc loc, Tag tag, fe::Sym sym)
61 Tok(fe::Loc loc, std::int64_t i64)
66 fe::Loc loc()
const {
return loc_; }
67 Tag tag()
const {
return tag_; }
68 bool isa(Tag tag)
const {
return tag == tag_; }
69 explicit operator bool()
const {
return tag_ != Tag::Nil; }
72 assert(isa(Tag::V_str) || isa(Tag::V_num));
75 std::int64_t i64()
const {
76 assert(isa(Tag::V_int));
80 static std::string_view tag2str(Tag tag) {
83 case Tag::t: return str;
88 default: std::unreachable();
92 friend std::ostream&
operator<<(std::ostream& o, Tok tok) {
93 if (tok.isa(Tag::V_str))
return o <<
'"' << tok.sym() <<
'"';
94 if (tok.isa(Tag::V_num))
return o << tok.sym();
95 if (tok.isa(Tag::V_int))
return o << tok.i64();
96 return o << tag2str(tok.tag());
114template<>
struct std::formatter<
pbqp::json::Tok> : fe::ostream_formatter {};
125std::int64_t to_i64(std::string_view sv) {
126 std::int64_t res = 0;
127 if (std::from_chars(sv.data(), sv.data() + sv.size(), res).ec == std::errc::result_out_of_range)
128 return sv.starts_with(
'-') ? std::numeric_limits<std::int64_t>::min()
129 : std::numeric_limits<std::int64_t>::max();
133class Lexer :
public fe::Lexer<1, Lexer> {
135 Lexer(fe::Driver& driver,
const fe::Src& src)
136 : fe::Lexer<1, Lexer>(src)
139 fe::Driver& driver() {
return driver_; }
145 if (accept(utf8::EoF))
return {loc_, Tag::EoF};
146 if (accept(utf8::isspace))
continue;
147 if (recover_utf8())
continue;
148 if (accept(
'{'))
return {loc_, Tag::D_brace_l};
149 if (accept(
'}'))
return {loc_, Tag::D_brace_r};
150 if (accept(
'['))
return {loc_, Tag::D_bracket_l};
151 if (accept(
']'))
return {loc_, Tag::D_bracket_r};
152 if (accept(
':'))
return {loc_, Tag::T_colon};
153 if (accept(
','))
return {loc_, Tag::T_comma};
154 if (accept(
'"'))
return lex_string();
155 if (ahead() ==
'-' || utf8::isdigit(ahead()))
return lex_number();
157 if (accept(utf8::isalpha)) {
158 accept_while(utf8::isalpha);
159#define CODE(t, str) \
160 if (view() == str) return {loc_, Tag::t};
163 error().e(loc_,
"unknown literal `{}`", view());
172 bool accept_digits() {
return !accept_while(utf8::isdigit).empty(); }
176 bool ok = accept_digits();
180 ok = accept_digits() && ok;
182 if (accept(
'e') || accept(
'E')) {
184 if (!accept(
'+')) accept(
'-');
185 ok = accept_digits() && ok;
187 if (!ok)
error().e(loc_,
"malformed number `{}`", view());
188 if (integer && ok)
return {loc_, to_i64(view())};
189 return {loc_, Tag::V_num, driver_.sym(view())};
195 accept_while_none_of(u8
'"', u8
'\\');
196 if (accept(
'"'))
return {loc_, Tag::V_str, driver_.sym(view().substr(1, view().
size() - 2))};
197 if (!accept(
'\\') || ahead() == utf8::EoF)
break;
200 error().e(loc_,
"unterminated string");
201 return {loc_, Tag::V_str, driver_.sym(view().substr(1))};
216 std::optional<Field> rows;
217 std::optional<Field> cols;
222class Parser :
public fe::Parser<Tok, Tag, 1, Parser> {
224 Parser(fe::Driver& driver,
const fe::Src& src)
225 : lexer_(driver, src) {
229 fe::Driver& driver() {
return lexer_.driver(); }
230 Lexer& lexer() {
return lexer_; }
232 void parse_instance(Instance& instance) {
233 parse_object(
"PBQP instance", [&](fe::Sym key) {
235 if (key ==
"nodes" ) parse_array(
"`nodes`", [
this] { parse_node(); });
236 else if (key ==
"edges" ) parse_array(
"`edges`", [
this] { parse_edge(); });
237 else if (key ==
"rn_priority") parse_rn_priority();
238 else parse_value(
"PBQP instance");
241 expect(Tag::EoF,
"PBQP instance");
242 if (
error().ok()) build(instance);
246 void parse_list(Tag l, Tag r, fe::Cite ctx,
auto&& parse_element) {
247 auto tok_l = expect(l, ctx);
249 auto _ = anchor(tok_l, r);
250 if (accept(r))
return;
253 }
while (accept(Tag::T_comma));
254 if (!expect(r, ctx)) {
255 recover([](Tag t) {
return t != Tag::EoF; }, ctx);
260 void parse_object(fe::Cite ctx,
auto&& parse_member) {
261 parse_list(Tag::D_brace_l, Tag::D_brace_r, ctx, [&] {
262 auto key = expect(Tag::V_str, ctx);
263 expect(Tag::T_colon, ctx);
264 parse_member(key ? key.sym() : fe::Sym());
268 void parse_array(fe::Cite ctx,
auto&& parse_element) {
269 parse_list(Tag::D_bracket_l, Tag::D_bracket_r, ctx, parse_element);
272 void parse_value(fe::Cite ctx) {
273 switch (ahead().tag()) {
274 case Tag::D_brace_l: parse_object(ctx, [&](fe::Sym) { parse_value(ctx); });
return;
275 case Tag::D_bracket_l: parse_array(ctx, [&] { parse_value(ctx); });
return;
276#define CODE(t, _) case Tag::t:
282 default: syntax_err(
"value", ctx);
286 Field parse_index(fe::Cite ctx) {
287 auto tok = expect(Tag::V_int, ctx);
289 if (tok.i64() < 0)
error().e(tok.loc(),
"expected a non-negative integer, got `{}`", tok);
290 return {tok.loc(),
static_cast<size_t>(tok.i64())};
293 Cost to_cost(Tok tok, std::int64_t value) {
295 error().e(tok.loc(),
"cost `{}` is out of range", tok);
301 Cost parse_cost(fe::Cite ctx) {
302 switch (ahead().tag()) {
305 return to_cost(tok, tok.i64());
309 if (tok.sym() ==
"inf")
return Cost::inf();
310 error().e(tok.loc(),
"expected a cost, got `{}`", tok);
314#define CODE(t, _) case Tag::t:
317 syntax_err(
"cost", ctx, lex());
319 default: syntax_err(
"cost", ctx);
return 0;
323 fe::Loc parse_costs(
Costs& costs, fe::Cite ctx) {
324 auto track = tracker();
326 parse_array(ctx, [&] { costs.push_back(parse_cost(ctx)); });
330 void parse_rn_priority() {
331 auto track = tracker();
332 rn_priority_.clear();
333 parse_array(
"`rn_priority`", [
this] { rn_priority_.push_back(parse_index(
"`rn_priority`").value); });
334 rn_priority_loc_ = track;
338 auto track = tracker();
341 parse_object(
"node", [&](fe::Sym key) {
343 costs_loc = parse_costs(costs,
"node `costs`");
347 if (!costs_loc)
return void(
error().
e(track,
"node without `costs`"));
348 if (costs.empty())
error().e(costs_loc,
"node {} has no options", nodes_.size());
349 nodes_.push_back(std::move(costs));
353 auto track = tracker();
355 std::optional<Field> src, dst;
356 parse_object(
"edge", [&](fe::Sym key) {
358 if (key ==
"src" ) src = parse_index(
"edge `src`");
359 else if (key ==
"dst" ) dst = parse_index(
"edge `dst`");
360 else if (key ==
"rows" ) edge.rows = parse_index(
"edge `rows`");
361 else if (key ==
"cols" ) edge.cols = parse_index(
"edge `cols`");
362 else if (key ==
"costs") edge.costs_loc = parse_costs(edge.costs,
"edge `costs`");
363 else parse_value(
"edge");
367 if (!src)
return void(
error().
e(edge.loc,
"edge without `src`"));
368 if (!dst)
return void(
error().
e(edge.loc,
"edge without `dst`"));
369 if (!edge.costs_loc)
return void(
error().
e(edge.loc,
"edge without `costs`"));
372 edges_.push_back(std::move(edge));
375 void build(Instance& instance) {
376 Graph& graph = instance.graph;
377 for (
const auto& costs : nodes_)
380 const auto known = [&](
const Field& field) {
381 if (field.value < graph.num_nodes())
return true;
382 error().e(field.loc,
"unknown node {}", field.value);
386 for (
const auto& edge : edges_) {
387 if (!
known(edge.src) || !
known(edge.dst))
continue;
388 const NodeId src = edge.src.value;
389 const NodeId dst = edge.dst.value;
391 error().e(edge.loc,
"self-edge on node {}", src);
395 error().e(edge.loc,
"duplicate edge between nodes {} and {}", src, dst);
398 const size_t rows = graph.num_options(src);
399 const size_t cols = graph.num_options(dst);
400 if (edge.rows && edge.rows->value != rows)
401 error().e(edge.rows->loc,
"`rows` is {}, but node {} has {} options", edge.rows->value, src, rows);
402 else if (edge.cols && edge.cols->value != cols)
403 error().e(edge.cols->loc,
"`cols` is {}, but node {} has {} options", edge.cols->value, dst, cols);
404 else if (edge.costs.size() != rows * cols)
405 error().e(edge.costs_loc,
"expected {} × {} costs, got {}", rows, cols, edge.costs.size());
407 graph.link(src, dst,
MatrixView(edge.costs.data(), rows, cols));
410 if (rn_priority_loc_ && rn_priority_.size() != graph.num_nodes())
411 error().e(rn_priority_loc_,
"expected {} priorities, got {}", graph.num_nodes(), rn_priority_.size());
412 instance.rn_priority = std::move(rn_priority_);
416 fe::Vector<Costs> nodes_;
417 fe::Vector<EdgeData> edges_;
418 fe::Vector<size_t> rn_priority_;
419 fe::Loc rn_priority_loc_;
422void write_costs(std::ostream& out, fe::View<Cost> costs) {
424 for (
size_t i = 0; i < costs.size(); ++i) {
425 if (i != 0) out <<
", ";
426 if (costs[i].is_inf())
429 std::print(out,
"{}", costs[i].value());
442 const fe::Src* src = driver.src().add(path, fe::SrcMap::slurp(in)).first;
443 json::Parser(driver, *src).parse_instance(instance);
444 driver.error().ack();
448 assert((rn_priority.empty() || rn_priority.size() == graph.
num_nodes())
449 &&
"write_json: rn_priority must have one entry per node");
451 std::println(out,
"{{");
453 std::print(out, R
"( "nodes": [)");
454 const char* separator =
"\n";
455 for (
const auto n : graph.
nodes()) {
456 std::print(out, R
"({} {{"costs": )", separator);
461 std::print(out,
"\n ],\n");
463 std::print(out, R
"( "edges": [)");
465 for (
const auto e : graph.
edges()) {
466 const auto [src, dst] = graph.
edge(e);
468 std::print(out, R
"({} {{"src": {}, "dst": {}, "rows": {}, "cols": {}, "costs": )", separator, src, dst,
470 json::write_costs(out, {matrix.data(), matrix.size()});
474 std::print(out,
"\n ]");
476 if (!rn_priority.empty()) std::print(out,
",\n \"rn_priority\": [{}]", fe::Join(rn_priority,
", "));
477 std::println(out,
"\n}}");
constexpr size_t size() const
constexpr size_t rows() const
constexpr size_t cols() const
constexpr T * data() const
static constexpr Cost inf()
static constexpr Cost min()
Ends edge(EdgeId e) const
static constexpr EdgeId npos
MatrixView edge_matrix(EdgeId e) const
Row-major with the src option as the row.
fe::View< Cost > node_costs(NodeId n) const
auto nodes() const
All node ids.
auto edges() const
All edge ids.
LamSet known(World &world)
The closed Cns with a body that get a convention of their own instead of the ABI.
std::ostream & operator<<(std::ostream &os, const Def *def)
Def::Dump::Expr: one Def, one line, no analysis - and the backend of std::formatter for every Def poi...
BasicMatrix< const Cost > MatrixView
void write_json(std::ostream &out, const Graph &graph, fe::View< size_t > rn_priority={})
Write the format that read_json reads.
fe::Vector< Cost, 4 > Costs
size_t NodeId
Identifier of a node in a Graph.
void read_json(std::istream &in, Instance &instance, const std::filesystem::path &path="<input>")
Read a PBQP instance into the empty instance:
A graph together with the optional rn_priority for solve.