MimIR
MimIR is my Intermediate Representation
Loading...
Searching...
No Matches
json.cpp
Go to the documentation of this file.
1#include "pbqp/json.h"
2
3#include <cassert>
4#include <charconv>
5#include <cstdint>
6
7#include <limits>
8#include <optional>
9#include <print>
10#include <string_view>
11#include <utility>
12
13#include <fe/driver.h>
14#include <fe/format.h>
15#include <fe/lexer.h>
16#include <fe/parser.h>
17
18namespace pbqp::json {
19
20namespace utf8 = fe::utf8;
21
22// clang-format off
23#define PBQP_JSON_KEY(m) \
24 m(K_true, "true") \
25 m(K_false, "false") \
26 m(K_null, "null") \
27
28#define PBQP_JSON_VAL(m) \
29 m(V_str, "<string>") \
30 m(V_int, "<integer>") \
31 m(V_num, "<number>") \
32
33#define PBQP_JSON_TOK(m) \
34 m(EoF, "<end of file>") \
35 m(D_brace_l, "{") \
36 m(D_brace_r, "}") \
37 m(D_bracket_l, "[") \
38 m(D_bracket_r, "]") \
39 m(T_colon, ":") \
40 m(T_comma, ",") // clang-format on
41
42namespace {
43
44class Tok {
45public:
46 enum class Tag {
47 Nil,
48#define CODE(t, _) t,
50#undef CODE
51 };
52
53 Tok() {}
54 Tok(fe::Loc loc, Tag tag)
55 : loc_(loc)
56 , tag_(tag) {}
57 Tok(fe::Loc loc, Tag tag, fe::Sym sym)
58 : loc_(loc)
59 , tag_(tag)
60 , sym_(sym) {}
61 Tok(fe::Loc loc, std::int64_t i64)
62 : loc_(loc)
63 , tag_(Tag::V_int)
64 , i64_(i64) {}
65
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; }
70
71 fe::Sym sym() const {
72 assert(isa(Tag::V_str) || isa(Tag::V_num));
73 return sym_;
74 }
75 std::int64_t i64() const {
76 assert(isa(Tag::V_int));
77 return i64_;
78 }
79
80 static std::string_view tag2str(Tag tag) {
81 switch (tag) {
82#define CODE(t, str) \
83 case Tag::t: return str;
87#undef CODE
88 default: std::unreachable();
89 }
90 }
91
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());
97 }
98
99private:
100 fe::Loc loc_;
101 Tag tag_ = Tag::Nil;
102 union {
103 fe::Sym sym_;
104 std::int64_t i64_;
105 };
106};
107
108} // namespace
109
110} // namespace pbqp::json
111
112#ifndef DOXYGEN
113// clang-format off
114template<> struct std::formatter<pbqp::json::Tok> : fe::ostream_formatter {};
115// clang-format on
116#endif
117
118namespace pbqp::json {
119
120namespace {
121
122using Tag = Tok::Tag;
123
124/// std::from_chars leaves @p res alone on overflow, so saturate instead.
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();
130 return res;
131}
132
133class Lexer : public fe::Lexer<1, Lexer> {
134public:
135 Lexer(fe::Driver& driver, const fe::Src& src)
136 : fe::Lexer<1, Lexer>(src)
137 , driver_(driver) {}
138
139 fe::Driver& driver() { return driver_; }
140
141 Tok lex() {
142 while (true) {
143 start();
144
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();
156
157 if (accept(utf8::isalpha)) {
158 accept_while(utf8::isalpha);
159#define CODE(t, str) \
160 if (view() == str) return {loc_, Tag::t};
162#undef CODE
163 error().e(loc_, "unknown literal `{}`", view());
164 continue;
165 }
166
167 recover_char();
168 }
169 }
170
171private:
172 bool accept_digits() { return !accept_while(utf8::isdigit).empty(); }
173
174 Tok lex_number() {
175 accept('-');
176 bool ok = accept_digits();
177 bool integer = true;
178 if (accept('.')) {
179 integer = false;
180 ok = accept_digits() && ok;
181 }
182 if (accept('e') || accept('E')) {
183 integer = false;
184 if (!accept('+')) accept('-');
185 ok = accept_digits() && ok;
186 }
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())};
190 }
191
192 /// Escapes stay verbatim; none of the keys or cost spellings needs one.
193 Tok lex_string() {
194 while (true) {
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;
198 next();
199 }
200 error().e(loc_, "unterminated string");
201 return {loc_, Tag::V_str, driver_.sym(view().substr(1))};
202 }
203
204 fe::Driver& driver_;
205};
206
207struct Field {
208 fe::Loc loc;
209 size_t value = 0;
210};
211
212struct EdgeData {
213 fe::Loc loc;
214 Field src;
215 Field dst;
216 std::optional<Field> rows;
217 std::optional<Field> cols;
218 fe::Loc costs_loc;
219 Costs costs;
220};
221
222class Parser : public fe::Parser<Tok, Tag, 1, Parser> {
223public:
224 Parser(fe::Driver& driver, const fe::Src& src)
225 : lexer_(driver, src) {
226 init();
227 }
228
229 fe::Driver& driver() { return lexer_.driver(); }
230 Lexer& lexer() { return lexer_; }
231
232 void parse_instance(Instance& instance) {
233 parse_object("PBQP instance", [&](fe::Sym key) {
234 // clang-format off
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");
239 // clang-format on
240 });
241 expect(Tag::EoF, "PBQP instance");
242 if (error().ok()) build(instance);
243 }
244
245private:
246 void parse_list(Tag l, Tag r, fe::Cite ctx, auto&& parse_element) {
247 auto tok_l = expect(l, ctx);
248 if (!tok_l) return;
249 auto _ = anchor(tok_l, r);
250 if (accept(r)) return;
251 do {
252 parse_element();
253 } while (accept(Tag::T_comma));
254 if (!expect(r, ctx)) {
255 recover([](Tag t) { return t != Tag::EoF; }, ctx);
256 accept(r);
257 }
258 }
259
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());
265 });
266 }
267
268 void parse_array(fe::Cite ctx, auto&& parse_element) {
269 parse_list(Tag::D_bracket_l, Tag::D_bracket_r, ctx, parse_element);
270 }
271
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:
279#undef CODE
280 lex();
281 return;
282 default: syntax_err("value", ctx);
283 }
284 }
285
286 Field parse_index(fe::Cite ctx) {
287 auto tok = expect(Tag::V_int, ctx);
288 if (!tok) return {};
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())};
291 }
292
293 Cost to_cost(Tok tok, std::int64_t value) {
294 if (value < Cost::min().value() || Cost::inf().value() <= value) {
295 error().e(tok.loc(), "cost `{}` is out of range", tok);
296 return 0;
297 }
298 return static_cast<Cost::Rep>(value);
299 }
300
301 Cost parse_cost(fe::Cite ctx) {
302 switch (ahead().tag()) {
303 case Tag::V_int: {
304 auto tok = lex();
305 return to_cost(tok, tok.i64());
306 }
307 case Tag::V_str: {
308 auto tok = lex();
309 if (tok.sym() == "inf") return Cost::inf();
310 error().e(tok.loc(), "expected a cost, got `{}`", tok);
311 return 0;
312 }
313 case Tag::V_num:
314#define CODE(t, _) case Tag::t:
316#undef CODE
317 syntax_err("cost", ctx, lex());
318 return 0;
319 default: syntax_err("cost", ctx); return 0;
320 }
321 }
322
323 fe::Loc parse_costs(Costs& costs, fe::Cite ctx) {
324 auto track = tracker();
325 costs.clear();
326 parse_array(ctx, [&] { costs.push_back(parse_cost(ctx)); });
327 return track;
328 }
329
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;
335 }
336
337 void parse_node() {
338 auto track = tracker();
339 Costs costs;
340 fe::Loc costs_loc;
341 parse_object("node", [&](fe::Sym key) {
342 if (key == "costs")
343 costs_loc = parse_costs(costs, "node `costs`");
344 else
345 parse_value("node");
346 });
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));
350 }
351
352 void parse_edge() {
353 auto track = tracker();
354 EdgeData edge;
355 std::optional<Field> src, dst;
356 parse_object("edge", [&](fe::Sym key) {
357 // clang-format off
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");
364 // clang-format on
365 });
366 edge.loc = track;
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`"));
370 edge.src = *src;
371 edge.dst = *dst;
372 edges_.push_back(std::move(edge));
373 }
374
375 void build(Instance& instance) {
376 Graph& graph = instance.graph;
377 for (const auto& costs : nodes_)
378 graph.add(costs);
379
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);
383 return false;
384 };
385
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;
390 if (src == dst) {
391 error().e(edge.loc, "self-edge on node {}", src);
392 continue;
393 }
394 if (graph.edge(src, dst) != Graph::npos) {
395 error().e(edge.loc, "duplicate edge between nodes {} and {}", src, dst);
396 continue;
397 }
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());
406 else
407 graph.link(src, dst, MatrixView(edge.costs.data(), rows, cols));
408 }
409
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_);
413 }
414
415 Lexer lexer_;
416 fe::Vector<Costs> nodes_;
417 fe::Vector<EdgeData> edges_;
418 fe::Vector<size_t> rn_priority_;
419 fe::Loc rn_priority_loc_;
420};
421
422void write_costs(std::ostream& out, fe::View<Cost> costs) {
423 out << '[';
424 for (size_t i = 0; i < costs.size(); ++i) {
425 if (i != 0) out << ", ";
426 if (costs[i].is_inf())
427 out << R"("inf")";
428 else
429 std::print(out, "{}", costs[i].value());
430 }
431 out << ']';
432}
433
434} // namespace
435
436} // namespace pbqp::json
437
438namespace pbqp {
439
440void read_json(std::istream& in, Instance& instance, const std::filesystem::path& path) {
441 fe::Driver driver;
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();
445}
446
447void write_json(std::ostream& out, const Graph& graph, fe::View<size_t> rn_priority) {
448 assert((rn_priority.empty() || rn_priority.size() == graph.num_nodes())
449 && "write_json: rn_priority must have one entry per node");
450
451 std::println(out, "{{");
452
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);
457 json::write_costs(out, graph.node_costs(n));
458 out << '}';
459 separator = ",\n";
460 }
461 std::print(out, "\n ],\n");
462
463 std::print(out, R"( "edges": [)");
464 separator = "\n";
465 for (const auto e : graph.edges()) {
466 const auto [src, dst] = graph.edge(e);
467 const MatrixView matrix = graph.edge_matrix(e);
468 std::print(out, R"({} {{"src": {}, "dst": {}, "rows": {}, "cols": {}, "costs": )", separator, src, dst,
469 matrix.rows(), matrix.cols());
470 json::write_costs(out, {matrix.data(), matrix.size()});
471 out << '}';
472 separator = ",\n";
473 }
474 std::print(out, "\n ]");
475
476 if (!rn_priority.empty()) std::print(out, ",\n \"rn_priority\": [{}]", fe::Join(rn_priority, ", "));
477 std::println(out, "\n}}");
478}
479
480} // namespace pbqp
constexpr size_t size() const
Definition graph.h:90
constexpr size_t rows() const
Definition graph.h:88
constexpr size_t cols() const
Definition graph.h:89
constexpr T * data() const
Definition graph.h:99
static constexpr Cost inf()
Definition graph.h:39
static constexpr Cost min()
Definition graph.h:40
int32_t Rep
Definition graph.h:33
A PBQP problem graph.
Definition graph.h:252
Ends edge(EdgeId e) const
Definition graph.h:303
static constexpr EdgeId npos
Definition graph.h:259
size_t num_nodes() const
Definition graph.h:312
MatrixView edge_matrix(EdgeId e) const
Row-major with the src option as the row.
Definition graph.h:287
fe::View< Cost > node_costs(NodeId n) const
Definition graph.h:284
auto nodes() const
All node ids.
Definition graph.h:309
auto edges() const
All edge ids.
Definition graph.h:310
#define PBQP_JSON_KEY(m)
Definition json.cpp:23
#define PBQP_JSON_TOK(m)
Definition json.cpp:33
#define PBQP_JSON_VAL(m)
Definition json.cpp:28
Tok::Tag Tag
Definition bind.cpp:11
LamSet known(World &world)
The closed Cns with a body that get a convention of their own instead of the ABI.
Definition phase.h:33
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...
Definition dump.cpp:1535
Definition dot.h:9
BasicMatrix< const Cost > MatrixView
Definition graph.h:186
void write_json(std::ostream &out, const Graph &graph, fe::View< size_t > rn_priority={})
Write the format that read_json reads.
Definition json.cpp:447
fe::Vector< Cost, 4 > Costs
Definition graph.h:66
size_t NodeId
Identifier of a node in a Graph.
Definition graph.h:25
void read_json(std::istream &in, Instance &instance, const std::filesystem::path &path="<input>")
Read a PBQP instance into the empty instance:
Definition json.cpp:440
A graph together with the optional rn_priority for solve.
Definition json.h:15
#define CODE(name,...)
Definition tok.h:52