Coverage Report

Created: 2026-11-03 04:34

/home/runner/work/LabNeura/LabNeura/src/labneura/eda/netlist/netlist_json.cpp
Line
Count
Source (jump to first uncovered line)
1
#include "labneura/eda/netlist.h"
2
3
#include <fstream>
4
#include <cctype>
5
#include <istream>
6
#include <ostream>
7
#include <sstream>
8
#include <stdexcept>
9
#include <string>
10
#include <utility>
11
12
namespace labneura::eda {
13
namespace {
14
15
244
void append_string(std::ostream& out, const std::string& text) {
16
244
    static constexpr char hex[] = "0123456789abcdef";
17
244
    out.put('"');
18
793
    for (const unsigned char ch : text) {
19
793
        switch (ch) {
20
0
            case '"': out << "\\\""; break;
21
0
            case '\\': out << "\\\\"; break;
22
0
            case '\b': out << "\\b"; break;
23
0
            case '\f': out << "\\f"; break;
24
0
            case '\n': out << "\\n"; break;
25
0
            case '\r': out << "\\r"; break;
26
0
            case '\t': out << "\\t"; break;
27
793
            default:
28
793
                if (ch < 0x20) {
29
0
                    out << "\\u00" << hex[ch >> 4] << hex[ch & 0x0f];
30
793
                } else {
31
793
                    out.put(static_cast<char>(ch));
32
793
                }
33
793
        }
34
793
    }
35
244
    out.put('"');
36
244
}
37
38
22
const char* expression_kind_name(ExpressionKind kind) {
39
22
    switch (kind) {
40
12
        case ExpressionKind::Identifier: return "identifier";
41
4
        case ExpressionKind::Literal: return "literal";
42
0
        case ExpressionKind::Unary: return "unary";
43
1
        case ExpressionKind::Binary: return "binary";
44
0
        case ExpressionKind::Conditional: return "conditional";
45
5
        case ExpressionKind::BitSelect: return "bit_select";
46
0
        case ExpressionKind::RangeSelect: return "range_select";
47
0
        case ExpressionKind::Concatenation: return "concatenation";
48
0
        case ExpressionKind::Opaque: return "opaque";
49
22
    }
50
0
    throw std::runtime_error("invalid expression kind in netlist");
51
22
}
52
53
22
void write_expression(std::ostream& out, const Expression& expression) {
54
22
    out << "{\"kind\":";
55
22
    append_string(out, expression_kind_name(expression.get_kind()));
56
22
    out << ",\"value\":";
57
22
    append_string(out, expression.get_value());
58
22
    out << ",\"source\":";
59
22
    append_string(out, expression.get_source());
60
22
    out << ",\"width\":" << expression.get_width() << ",\"operands\":[";
61
22
    bool first = true;
62
22
    for (const auto& operand : expression.get_operands()) {
63
12
        if (!first) out.put(',');
64
12
        write_expression(out, operand);
65
12
        first = false;
66
12
    }
67
22
    out << "]}";
68
22
}
69
70
25
const char* port_direction_name(PortDirection direction) {
71
25
    switch (direction) {
72
17
        case PortDirection::Input: return "input";
73
8
        case PortDirection::Output: return "output";
74
0
        case PortDirection::InOut: return "inout";
75
25
    }
76
0
    throw std::runtime_error("invalid port direction in netlist");
77
25
}
78
79
28
const char* net_type_name(NetType type) {
80
28
    switch (type) {
81
17
        case NetType::Input: return "input";
82
8
        case NetType::Output: return "output";
83
0
        case NetType::InOut: return "inout";
84
3
        case NetType::Internal: return "internal";
85
28
    }
86
0
    throw std::runtime_error("invalid net type in netlist");
87
28
}
88
89
void write_index(std::ostream& out,
90
212
                 const std::optional<std::int64_t>& index) {
91
212
    if (index) out << *index;
92
162
    else out << "null";
93
212
}
94
95
8
void write_module(std::ostream& out, const Module& module) {
96
8
    out << "{\"name\":";
97
8
    append_string(out, module.get_name());
98
8
    out << ",\"hierarchy_instance_name\":";
99
8
    append_string(out, module.get_hierarchy_instance_name());
100
8
    out << ",\"is_behavioral\":" << (module.is_behavioral() ? "true" : "false")
101
8
        << ",\"ports\":[";
102
8
    bool first = true;
103
25
    for (const auto& port : module.get_ports()) {
104
25
        if (!first) out.put(',');
105
25
        out << "{\"name\":";
106
25
        append_string(out, port.get_name());
107
25
        out << ",\"direction\":";
108
25
        append_string(out, port_direction_name(port.get_direction()));
109
25
        out << ",\"width\":" << port.get_width() << ",\"left_index\":";
110
25
        write_index(out, port.get_left_index());
111
25
        out << ",\"right_index\":";
112
25
        write_index(out, port.get_right_index());
113
25
        out << ",\"unpacked_left_index\":";
114
25
        write_index(out, port.get_unpacked_left_index());
115
25
        out << ",\"unpacked_right_index\":";
116
25
        write_index(out, port.get_unpacked_right_index());
117
25
        out << ",\"packed_width\":" << port.get_packed_width();
118
25
        out.put('}');
119
25
        first = false;
120
25
    }
121
8
    out << "],\"nets\":[";
122
8
    first = true;
123
28
    for (const auto& net : module.get_nets()) {
124
28
        if (!first) out.put(',');
125
28
        out << "{\"name\":";
126
28
        append_string(out, net.get_name());
127
28
        out << ",\"kind\":";
128
28
        append_string(out, net_type_name(net.get_kind()));
129
28
        out << ",\"width\":" << net.get_width() << ",\"left_index\":";
130
28
        write_index(out, net.get_left_index());
131
28
        out << ",\"right_index\":";
132
28
        write_index(out, net.get_right_index());
133
28
        out << ",\"unpacked_left_index\":";
134
28
        write_index(out, net.get_unpacked_left_index());
135
28
        out << ",\"unpacked_right_index\":";
136
28
        write_index(out, net.get_unpacked_right_index());
137
28
        out << ",\"packed_width\":" << net.get_packed_width();
138
28
        out.put('}');
139
28
        first = false;
140
28
    }
141
8
    out << "],\"instances\":[";
142
8
    first = true;
143
8
    for (const auto& instance : module.get_instances()) {
144
7
        if (instance.get_cell()) {
145
0
            throw std::runtime_error(
146
0
                "JSON netlist I/O currently supports parsed and generic-mapped "
147
0
                "netlists, not technology-mapped cell metadata");
148
0
        }
149
7
        if (!first) out.put(',');
150
7
        out << "{\"name\":";
151
7
        append_string(out, instance.get_name());
152
7
        out << ",\"cell_type\":";
153
7
        append_string(out, instance.get_cell_type());
154
7
        out << ",\"connections\":[";
155
7
        bool first_connection = true;
156
21
        for (const auto& connection : instance.get_connections()) {
157
21
            if (!first_connection) out.put(',');
158
21
            out << "{\"pin\":";
159
21
            append_string(out, connection.get_pin());
160
21
            out << ",\"net\":";
161
21
            append_string(out, connection.get_net());
162
21
            out.put('}');
163
21
            first_connection = false;
164
21
        }
165
7
        out << "],\"parameters\":{";
166
7
        bool first_parameter = true;
167
7
        for (const auto& [name, value] : instance.get_parameters()) {
168
0
            if (!first_parameter) out.put(',');
169
0
            append_string(out, name);
170
0
            out.put(':');
171
0
            append_string(out, value);
172
0
            first_parameter = false;
173
0
        }
174
7
        out << "},\"user_defined_primitive\":"
175
7
            << (instance.is_user_defined_primitive() ? "true" : "false")
176
7
            << ",\"sequential_primitive\":"
177
7
            << (instance.is_sequential_primitive() ? "true" : "false")
178
7
            << ",\"primitive_table\":[";
179
7
        bool first_row = true;
180
7
        for (const auto& row : instance.get_primitive_table()) {
181
0
            if (!first_row) out.put(',');
182
0
            out << "{\"inputs\":";
183
0
            append_string(out, row.inputs);
184
0
            out << ",\"output\":";
185
0
            append_string(out, std::string(1, row.output));
186
0
            out.put('}');
187
0
            first_row = false;
188
0
        }
189
7
        out << "]}";
190
7
        first = false;
191
7
    }
192
8
    out << "],\"assignments\":[";
193
8
    first = true;
194
8
    for (const auto& assignment : module.get_assignments()) {
195
5
        if (!first) out.put(',');
196
5
        out << "{\"lhs_expression\":";
197
5
        write_expression(out, assignment.get_lhs_expression());
198
5
        out << ",\"rhs_expression\":";
199
5
        write_expression(out, assignment.get_rhs_expression());
200
5
        out.put('}');
201
5
        first = false;
202
5
    }
203
8
    out << "],\"child_modules\":[";
204
8
    first = true;
205
8
    for (const auto& child : module.get_child_modules()) {
206
2
        if (!first) out.put(',');
207
2
        write_module(out, child);
208
2
        first = false;
209
2
    }
210
8
    out << "]}";
211
8
}
212
213
14
void validate_json_module(const Module& module) {
214
14
    for (const auto& instance : module.get_instances()) {
215
12
        if (instance.get_cell()) {
216
0
            throw std::runtime_error(
217
0
                "JSON netlist I/O currently supports parsed and generic-mapped "
218
0
                "netlists, not technology-mapped cell metadata");
219
0
        }
220
12
    }
221
14
    for (const auto& child : module.get_child_modules()) {
222
4
        validate_json_module(child);
223
4
    }
224
14
}
225
226
class JsonReader {
227
public:
228
7
    explicit JsonReader(std::istream& input) : input_(input) {}
229
230
7
    Module read() {
231
7
        expect('{');
232
7
        std::string format;
233
7
        unsigned version = 0;
234
7
        bool has_modules = false;
235
7
        bool has_root_module = false;
236
7
        Module result;
237
22
        while (!consume('}')) {
238
21
            const auto key = string();
239
21
            expect(':');
240
21
            if (key == "format") {
241
7
                format = string();
242
14
            } else if (key == "version") {
243
7
                version = unsigned_number();
244
7
            } else if (key == "modules") {
245
7
                expect('[');
246
7
                if (!consume(']')) {
247
6
                    result = module();
248
6
                    has_root_module = true;
249
6
                    if (!consume(']')) {
250
0
                        expect(',');
251
0
                        skip_value();
252
0
                        while (consume(',')) skip_value();
253
0
                        expect(']');
254
0
                        fail("module JSON reader accepts one root module at a time");
255
0
                    }
256
6
                }
257
7
                has_modules = true;
258
7
            } else {
259
0
                skip_value();
260
0
            }
261
21
            if (!consume(',')) {
262
6
                expect('}');
263
6
                break;
264
6
            }
265
21
        }
266
7
        whitespace();
267
7
        if (peek() != std::char_traits<char>::eof()) {
268
0
            fail("trailing data after JSON object");
269
0
        }
270
7
        if (format != "eda-netlist") fail("unsupported JSON netlist format");
271
7
        if (version != 1 && version != 2) fail("unsupported JSON netlist version");
272
7
        if (!has_modules) fail("JSON netlist is missing modules");
273
7
        if (!has_root_module) fail("modules must contain exactly one module");
274
7
        return result;
275
7
    }
276
277
private:
278
    std::istream& input_;
279
    std::size_t position_ = 0;
280
281
2
    [[noreturn]] void fail(const std::string& message) const {
282
2
        throw std::runtime_error("invalid JSON netlist at byte " +
283
2
                                 std::to_string(position_) + ": " + message);
284
2
    }
285
286
3.14k
    void whitespace() {
287
3.23k
        while (peek() == ' ' || peek() == '\t' || peek() == '\r' ||
288
3.23k
               peek() == '\n') {
289
87
            (void)get();
290
87
        }
291
3.14k
    }
292
293
23.5k
    int peek() {
294
23.5k
        return input_.peek();
295
23.5k
    }
296
297
9.51k
    char get() {
298
9.51k
        const auto value = input_.get();
299
9.51k
        if (value == std::char_traits<char>::eof()) fail("unexpected end of file");
300
9.51k
        ++position_;
301
9.51k
        return static_cast<char>(value);
302
9.51k
    }
303
304
2.84k
    bool consume(char ch) {
305
2.84k
        whitespace();
306
2.84k
        if (peek() == ch) {
307
2.12k
            (void)get();
308
2.12k
            return true;
309
2.12k
        }
310
716
        return false;
311
2.84k
    }
312
313
1.59k
    void expect(char ch) {
314
1.59k
        if (!consume(ch)) fail(std::string("expected '") + ch + "'");
315
1.59k
    }
316
317
0
    static void append_utf8(std::string& out, unsigned codepoint) {
318
0
        if (codepoint <= 0x7f) {
319
0
            out.push_back(static_cast<char>(codepoint));
320
0
        } else if (codepoint <= 0x7ff) {
321
0
            out.push_back(static_cast<char>(0xc0 | (codepoint >> 6)));
322
0
            out.push_back(static_cast<char>(0x80 | (codepoint & 0x3f)));
323
0
        } else if (codepoint <= 0xffff) {
324
0
            out.push_back(static_cast<char>(0xe0 | (codepoint >> 12)));
325
0
            out.push_back(static_cast<char>(0x80 | ((codepoint >> 6) & 0x3f)));
326
0
            out.push_back(static_cast<char>(0x80 | (codepoint & 0x3f)));
327
0
        } else {
328
0
            out.push_back(static_cast<char>(0xf0 | (codepoint >> 18)));
329
0
            out.push_back(static_cast<char>(0x80 | ((codepoint >> 12) & 0x3f)));
330
0
            out.push_back(static_cast<char>(0x80 | ((codepoint >> 6) & 0x3f)));
331
0
            out.push_back(static_cast<char>(0x80 | (codepoint & 0x3f)));
332
0
        }
333
0
    }
334
335
0
    unsigned hex4() {
336
0
        unsigned value = 0;
337
0
        for (int i = 0; i < 4; ++i) {
338
0
            const char ch = get();
339
0
            value <<= 4;
340
0
            if (ch >= '0' && ch <= '9') value |= static_cast<unsigned>(ch - '0');
341
0
            else if (ch >= 'a' && ch <= 'f') value |= static_cast<unsigned>(ch - 'a' + 10);
342
0
            else if (ch >= 'A' && ch <= 'F') value |= static_cast<unsigned>(ch - 'A' + 10);
343
0
            else fail("invalid unicode escape");
344
0
        }
345
0
        return value;
346
0
    }
347
348
745
    std::string string() {
349
745
        expect('"');
350
745
        std::string result;
351
6.63k
        while (peek() != std::char_traits<char>::eof()) {
352
6.63k
            const unsigned char ch = static_cast<unsigned char>(get());
353
6.63k
            if (ch == '"') return result;
354
5.89k
            if (ch < 0x20) fail("unescaped control character in string");
355
5.89k
            if (ch != '\\') {
356
5.89k
                result.push_back(static_cast<char>(ch));
357
5.89k
                continue;
358
5.89k
            }
359
0
            switch (get()) {
360
0
                case '"': result.push_back('"'); break;
361
0
                case '\\': result.push_back('\\'); break;
362
0
                case '/': result.push_back('/'); break;
363
0
                case 'b': result.push_back('\b'); break;
364
0
                case 'f': result.push_back('\f'); break;
365
0
                case 'n': result.push_back('\n'); break;
366
0
                case 'r': result.push_back('\r'); break;
367
0
                case 't': result.push_back('\t'); break;
368
0
                case 'u': {
369
0
                    unsigned codepoint = hex4();
370
0
                    if (codepoint >= 0xd800 && codepoint <= 0xdbff) {
371
0
                        if (get() != '\\' || get() != 'u') {
372
0
                            fail("missing low surrogate");
373
0
                        }
374
0
                        const unsigned low = hex4();
375
0
                        if (low < 0xdc00 || low > 0xdfff) fail("invalid low surrogate");
376
0
                        codepoint = 0x10000 + ((codepoint - 0xd800) << 10) +
377
0
                                    (low - 0xdc00);
378
0
                    } else if (codepoint >= 0xdc00 && codepoint <= 0xdfff) {
379
0
                        fail("unexpected low surrogate");
380
0
                    }
381
0
                    append_utf8(result, codepoint);
382
0
                    break;
383
0
                }
384
0
                default: fail("invalid string escape");
385
0
            }
386
0
        }
387
0
        fail("unterminated string");
388
0
    }
389
390
126
    void literal(const char* value) {
391
646
        while (*value) {
392
520
            if (peek() == std::char_traits<char>::eof() || get() != *value++) {
393
0
                fail("invalid literal");
394
0
            }
395
520
        }
396
126
    }
397
398
16
    bool boolean() {
399
16
        whitespace();
400
16
        if (peek() == 't') {
401
0
            literal("true");
402
0
            return true;
403
0
        }
404
16
        if (peek() == 'f') {
405
16
            literal("false");
406
16
            return false;
407
16
        }
408
0
        fail("expected boolean");
409
0
    }
410
411
101
    std::size_t unsigned_number() {
412
101
        whitespace();
413
101
        std::string digits;
414
101
        if (peek() == '0') {
415
4
            digits.push_back(get());
416
4
            if (peek() >= '0' && peek() <= '9') {
417
0
                fail("leading zero in integer");
418
0
            }
419
97
        } else {
420
199
            while (peek() >= '0' && peek() <= '9') digits.push_back(get());
421
97
        }
422
101
        if (digits.empty()) fail("expected non-negative integer");
423
101
        try {
424
101
            return static_cast<std::size_t>(std::stoull(digits));
425
101
        } catch (const std::exception&) {
426
0
            fail("integer is out of range");
427
0
        }
428
101
    }
429
430
152
    std::optional<std::int64_t> optional_index() {
431
152
        whitespace();
432
152
        if (peek() == 'n') {
433
110
            literal("null");
434
110
            return std::nullopt;
435
110
        }
436
42
        std::string number;
437
42
        if (peek() == '-') number.push_back(get());
438
42
        if (peek() == '0') {
439
8
            number.push_back(get());
440
8
            if (peek() >= '0' && peek() <= '9') {
441
0
                fail("leading zero in range index");
442
0
            }
443
34
        } else {
444
68
            while (peek() >= '0' && peek() <= '9') number.push_back(get());
445
34
        }
446
42
        if (number.empty() || number == "-") fail("expected integer or null");
447
42
        try {
448
42
            return std::stoll(number);
449
42
        } catch (const std::exception&) {
450
0
            fail("range index is out of range");
451
0
        }
452
42
    }
453
454
0
    void skip_number() {
455
0
        whitespace();
456
0
        if (peek() == '-') (void)get();
457
0
        if (peek() == '0') {
458
0
            (void)get();
459
0
            if (peek() >= '0' && peek() <= '9') fail("invalid JSON number");
460
0
        } else {
461
0
            if (peek() < '1' || peek() > '9') fail("expected JSON value");
462
0
            while (peek() >= '0' && peek() <= '9') (void)get();
463
0
        }
464
0
        if (peek() == '.') {
465
0
            (void)get();
466
0
            if (peek() < '0' || peek() > '9') fail("invalid JSON fraction");
467
0
            while (peek() >= '0' && peek() <= '9') (void)get();
468
0
        }
469
0
        if (peek() == 'e' || peek() == 'E') {
470
0
            (void)get();
471
0
            if (peek() == '+' || peek() == '-') (void)get();
472
0
            if (peek() < '0' || peek() > '9') fail("invalid JSON exponent");
473
0
            while (peek() >= '0' && peek() <= '9') (void)get();
474
0
        }
475
0
    }
476
477
0
    void skip_value() {
478
0
        whitespace();
479
0
        if (peek() == std::char_traits<char>::eof()) fail("expected JSON value");
480
0
        if (peek() == '"') {
481
0
            (void)string();
482
0
        } else if (peek() == '{') {
483
0
            expect('{');
484
0
            if (consume('}')) return;
485
0
            do {
486
0
                (void)string();
487
0
                expect(':');
488
0
                skip_value();
489
0
            } while (consume(','));
490
0
            expect('}');
491
0
        } else if (peek() == '[') {
492
0
            expect('[');
493
0
            if (consume(']')) return;
494
0
            do { skip_value(); } while (consume(','));
495
0
            expect(']');
496
0
        } else if (peek() == 't') {
497
0
            literal("true");
498
0
        } else if (peek() == 'f') {
499
0
            literal("false");
500
0
        } else if (peek() == 'n') {
501
0
            literal("null");
502
0
        } else {
503
0
            skip_number();
504
0
        }
505
0
    }
506
507
    template <typename Callback>
508
62
    void array(Callback&& callback) {
509
62
        expect('[');
510
62
        if (consume(']')) return;
511
77
        do { callback(); } while (consume(','));
512
33
        expect(']');
513
33
    }
netlist_json.cpp:_ZN8labneura3eda12_GLOBAL__N_110JsonReader5arrayIZNS2_6moduleEvEUlvE_EEvOT_
Line
Count
Source
508
7
    void array(Callback&& callback) {
509
7
        expect('[');
510
7
        if (consume(']')) return;
511
19
        do { callback(); } while (consume(','));
512
7
        expect(']');
513
7
    }
netlist_json.cpp:_ZN8labneura3eda12_GLOBAL__N_110JsonReader5arrayIZNS2_6moduleEvEUlvE0_EEvOT_
Line
Count
Source
508
7
    void array(Callback&& callback) {
509
7
        expect('[');
510
7
        if (consume(']')) return;
511
21
        do { callback(); } while (consume(','));
512
7
        expect(']');
513
7
    }
netlist_json.cpp:_ZN8labneura3eda12_GLOBAL__N_110JsonReader5arrayIZNS2_6moduleEvEUlvE1_EEvOT_
Line
Count
Source
508
7
    void array(Callback&& callback) {
509
7
        expect('[');
510
7
        if (consume(']')) return;
511
6
        do { callback(); } while (consume(','));
512
5
        expect(']');
513
5
    }
netlist_json.cpp:_ZN8labneura3eda12_GLOBAL__N_110JsonReader5arrayIZNS2_8instanceEvEUlvE_EEvOT_
Line
Count
Source
508
5
    void array(Callback&& callback) {
509
5
        expect('[');
510
5
        if (consume(']')) return;
511
15
        do { callback(); } while (consume(','));
512
5
        expect(']');
513
5
    }
netlist_json.cpp:_ZN8labneura3eda12_GLOBAL__N_110JsonReader5arrayIZNS2_8instanceEvEUlvE0_EEvOT_
Line
Count
Source
508
5
    void array(Callback&& callback) {
509
5
        expect('[');
510
5
        if (consume(']')) return;
511
0
        do { callback(); } while (consume(','));
512
0
        expect(']');
513
0
    }
netlist_json.cpp:_ZN8labneura3eda12_GLOBAL__N_110JsonReader5arrayIZNS2_6moduleEvEUlvE2_EEvOT_
Line
Count
Source
508
7
    void array(Callback&& callback) {
509
7
        expect('[');
510
7
        if (consume(']')) return;
511
4
        do { callback(); } while (consume(','));
512
2
        expect(']');
513
2
    }
netlist_json.cpp:_ZN8labneura3eda12_GLOBAL__N_110JsonReader5arrayIZNS2_10expressionEvEUlvE_EEvOT_
Line
Count
Source
508
18
    void array(Callback&& callback) {
509
18
        expect('[');
510
18
        if (consume(']')) return;
511
10
        do { callback(); } while (consume(','));
512
5
        expect(']');
513
5
    }
netlist_json.cpp:_ZN8labneura3eda12_GLOBAL__N_110JsonReader5arrayIZNS2_6moduleEvEUlvE3_EEvOT_
Line
Count
Source
508
6
    void array(Callback&& callback) {
509
6
        expect('[');
510
6
        if (consume(']')) return;
511
2
        do { callback(); } while (consume(','));
512
2
        expect(']');
513
2
    }
514
515
18
    ExpressionKind expression_kind(const std::string& name) {
516
18
        if (name == "identifier") return ExpressionKind::Identifier;
517
9
        if (name == "literal") return ExpressionKind::Literal;
518
5
        if (name == "unary") return ExpressionKind::Unary;
519
5
        if (name == "binary") return ExpressionKind::Binary;
520
4
        if (name == "conditional") return ExpressionKind::Conditional;
521
4
        if (name == "bit_select") return ExpressionKind::BitSelect;
522
0
        if (name == "range_select") return ExpressionKind::RangeSelect;
523
0
        if (name == "concatenation") return ExpressionKind::Concatenation;
524
0
        if (name == "opaque") return ExpressionKind::Opaque;
525
0
        fail("unknown expression kind");
526
0
    }
527
528
18
    Expression expression() {
529
18
        expect('{');
530
18
        ExpressionKind kind = ExpressionKind::Opaque;
531
18
        std::string value;
532
18
        std::string source;
533
18
        std::size_t width = 0;
534
18
        std::vector<Expression> operands;
535
90
        while (!consume('}')) {
536
90
            const auto key = string();
537
90
            expect(':');
538
90
            if (key == "kind") kind = expression_kind(string());
539
72
            else if (key == "value") value = string();
540
54
            else if (key == "source") source = string();
541
36
            else if (key == "width") width = unsigned_number();
542
18
            else if (key == "operands") {
543
18
                array([&] { operands.push_back(expression()); });
544
18
            } else skip_value();
545
90
            if (!consume(',')) { expect('}'); break; }
546
90
        }
547
18
        return Expression(kind, std::move(value), std::move(source),
548
18
                          std::move(operands), width);
549
18
    }
550
551
19
    PortDirection port_direction() {
552
19
        const auto value = string();
553
19
        if (value == "input") return PortDirection::Input;
554
6
        if (value == "output") return PortDirection::Output;
555
0
        if (value == "inout") return PortDirection::InOut;
556
0
        fail("unknown port direction");
557
0
    }
558
559
20
    NetType net_type() {
560
20
        const auto value = string();
561
20
        if (value == "input") return NetType::Input;
562
8
        if (value == "output") return NetType::Output;
563
2
        if (value == "inout") return NetType::InOut;
564
2
        if (value == "internal") return NetType::Internal;
565
0
        fail("unknown net type");
566
0
    }
567
568
19
    Port port() {
569
19
        expect('{');
570
19
        std::string name;
571
19
        PortDirection direction = PortDirection::Input;
572
19
        std::size_t width = 1;
573
19
        std::optional<std::int64_t> left;
574
19
        std::optional<std::int64_t> right;
575
19
        std::optional<std::int64_t> unpacked_left;
576
19
        std::optional<std::int64_t> unpacked_right;
577
19
        std::size_t packed_width = 0;
578
146
        while (!consume('}')) {
579
146
            const auto key = string();
580
146
            expect(':');
581
146
            if (key == "name") name = string();
582
127
            else if (key == "direction") direction = port_direction();
583
108
            else if (key == "width") width = unsigned_number();
584
90
            else if (key == "left_index") left = optional_index();
585
72
            else if (key == "right_index") right = optional_index();
586
54
            else if (key == "unpacked_left_index") unpacked_left = optional_index();
587
36
            else if (key == "unpacked_right_index") unpacked_right = optional_index();
588
18
            else if (key == "packed_width") packed_width = unsigned_number();
589
0
            else skip_value();
590
146
            if (!consume(',')) { expect('}'); break; }
591
146
        }
592
19
        if (name.empty() || width == 0) fail("invalid port");
593
19
        return Port(std::move(name), direction, width, left, right,
594
19
                    unpacked_left, unpacked_right, packed_width);
595
19
    }
596
597
21
    Net net() {
598
21
        whitespace();
599
21
        if (peek() == '"') return Net(string(), NetType::Internal);
600
20
        expect('{');
601
20
        std::string name;
602
20
        NetType kind = NetType::Internal;
603
20
        std::size_t width = 1;
604
20
        std::optional<std::int64_t> left;
605
20
        std::optional<std::int64_t> right;
606
20
        std::optional<std::int64_t> unpacked_left;
607
20
        std::optional<std::int64_t> unpacked_right;
608
20
        std::size_t packed_width = 0;
609
160
        while (!consume('}')) {
610
160
            const auto key = string();
611
160
            expect(':');
612
160
            if (key == "name") name = string();
613
140
            else if (key == "kind") kind = net_type();
614
120
            else if (key == "width") width = unsigned_number();
615
100
            else if (key == "left_index") left = optional_index();
616
80
            else if (key == "right_index") right = optional_index();
617
60
            else if (key == "unpacked_left_index") unpacked_left = optional_index();
618
40
            else if (key == "unpacked_right_index") unpacked_right = optional_index();
619
20
            else if (key == "packed_width") packed_width = unsigned_number();
620
0
            else skip_value();
621
160
            if (!consume(',')) { expect('}'); break; }
622
160
        }
623
20
        if (name.empty() || width == 0) fail("invalid net");
624
20
        return Net(std::move(name), kind, width, left, right,
625
20
                   unpacked_left, unpacked_right, packed_width);
626
21
    }
627
628
15
    PinConnection connection() {
629
15
        expect('{');
630
15
        std::string pin;
631
15
        std::string net_name;
632
30
        while (!consume('}')) {
633
30
            const auto key = string();
634
30
            expect(':');
635
30
            if (key == "pin") pin = string();
636
15
            else if (key == "net") net_name = string();
637
0
            else skip_value();
638
30
            if (!consume(',')) { expect('}'); break; }
639
30
        }
640
15
        if (pin.empty()) fail("connection has no pin");
641
15
        return PinConnection(std::move(pin), std::move(net_name));
642
15
    }
643
644
6
    Instance instance() {
645
6
        expect('{');
646
6
        std::string name;
647
6
        std::string type;
648
6
        std::vector<PinConnection> connections;
649
6
        std::map<std::string, std::string> parameters;
650
6
        std::vector<UserDefinedPrimitiveRow> table;
651
6
        bool udp = false;
652
6
        bool sequential = false;
653
38
        while (!consume('}')) {
654
38
            const auto key = string();
655
38
            expect(':');
656
38
            if (key == "name") name = string();
657
32
            else if (key == "cell_type") type = string();
658
26
            else if (key == "connections") {
659
6
                whitespace();
660
6
                if (peek() == '[') {
661
15
                    array([&] { connections.push_back(connection()); });
662
5
                } else {
663
1
                    expect('{');
664
1
                    if (!consume('}')) {
665
2
                        do {
666
2
                            auto pin = string();
667
2
                            expect(':');
668
2
                            connections.emplace_back(std::move(pin), string());
669
2
                        } while (consume(','));
670
1
                        expect('}');
671
1
                    }
672
1
                }
673
20
            } else if (key == "parameters") {
674
5
                expect('{');
675
5
                if (!consume('}')) {
676
0
                    do {
677
0
                        const auto parameter = string();
678
0
                        expect(':');
679
0
                        parameters[parameter] = string();
680
0
                    } while (consume(','));
681
0
                    expect('}');
682
0
                }
683
15
            } else if (key == "user_defined_primitive") udp = boolean();
684
10
            else if (key == "sequential_primitive") sequential = boolean();
685
5
            else if (key == "primitive_table") {
686
5
                array([&] {
687
0
                    expect('{');
688
0
                    std::string inputs;
689
0
                    std::string output;
690
0
                    while (!consume('}')) {
691
0
                        const auto field = string();
692
0
                        expect(':');
693
0
                        if (field == "inputs") inputs = string();
694
0
                        else if (field == "output") output = string();
695
0
                        else skip_value();
696
0
                        if (!consume(',')) { expect('}'); break; }
697
0
                    }
698
0
                    if (output.size() != 1) fail("invalid UDP row");
699
0
                    table.push_back({std::move(inputs), output.front()});
700
0
                });
701
5
            } else skip_value();
702
38
            if (!consume(',')) { expect('}'); break; }
703
38
        }
704
6
        if (name.empty() || type.empty()) fail("invalid instance");
705
6
        return Instance(std::move(name), std::move(type), std::move(connections),
706
6
                        std::nullopt, std::move(parameters), udp, std::move(table),
707
6
                        sequential);
708
6
    }
709
710
4
    ContinuousAssignment assignment() {
711
4
        expect('{');
712
4
        Expression lhs;
713
4
        Expression rhs;
714
4
        bool has_lhs = false;
715
4
        bool has_rhs = false;
716
8
        while (!consume('}')) {
717
8
            const auto key = string();
718
8
            expect(':');
719
8
            if (key == "lhs_expression") {
720
4
                lhs = expression();
721
4
                has_lhs = true;
722
4
            } else if (key == "rhs_expression") {
723
4
                rhs = expression();
724
4
                has_rhs = true;
725
4
            } else {
726
0
                skip_value();
727
0
            }
728
8
            if (!consume(',')) { expect('}'); break; }
729
8
        }
730
4
        if (!has_lhs || !has_rhs) fail("assignment lacks expression tree");
731
4
        return ContinuousAssignment(std::move(lhs), std::move(rhs));
732
4
    }
733
734
8
    Module module() {
735
8
        expect('{');
736
8
        std::string name;
737
8
        std::string hierarchy_name;
738
8
        bool behavioral = false;
739
8
        std::vector<Port> ports;
740
8
        std::vector<Net> nets;
741
8
        std::vector<Instance> instances;
742
8
        std::vector<ContinuousAssignment> assignments;
743
8
        std::vector<Module> children;
744
54
        while (!consume('}')) {
745
53
            const auto key = string();
746
53
            expect(':');
747
53
            if (key == "name") name = string();
748
46
            else if (key == "hierarchy_instance_name") hierarchy_name = string();
749
40
            else if (key == "is_behavioral") behavioral = boolean();
750
34
            else if (key == "ports") array([&] { ports.push_back(port()); });
751
27
            else if (key == "nets") array([&] { nets.push_back(net()); });
752
20
            else if (key == "instances") array([&] { instances.push_back(instance()); });
753
13
            else if (key == "assignments") array([&] { assignments.push_back(assignment()); });
754
6
            else if (key == "child_modules") {
755
6
                array([&] { children.push_back(module()); });
756
6
            } else {
757
0
                skip_value();
758
0
            }
759
53
            if (!consume(',')) { expect('}'); break; }
760
53
        }
761
8
        if (name.empty()) fail("module has no name");
762
8
        return Module(std::move(name), std::move(ports), std::move(nets),
763
8
                      std::move(instances), std::move(assignments), behavioral,
764
8
                      std::move(hierarchy_name), std::move(children));
765
8
    }
766
};
767
768
6
void write_json_stream(std::ostream& out, const Module& module) {
769
6
    validate_json_module(module);
770
6
    out << "{\"format\":\"eda-netlist\",\"version\":2,\"modules\":[";
771
6
    write_module(out, module);
772
6
    out << "]}\n";
773
6
    if (!out) throw std::runtime_error("failed writing JSON netlist");
774
6
}
775
776
}  // namespace
777
778
2
std::string to_json(const Module& module) {
779
2
    std::ostringstream output;
780
2
    write_json_stream(output, module);
781
2
    return output.str();
782
2
}
783
784
4
void write_json(const Module& module, const std::string& path) {
785
4
    validate_json_module(module);
786
4
    std::ofstream output(path);
787
4
    if (!output) throw std::runtime_error("could not open JSON output: " + path);
788
4
    write_json_stream(output, module);
789
4
}
790
791
7
Module read_json(const std::string& path) {
792
7
    std::ifstream input(path);
793
7
    if (!input) throw std::runtime_error("could not open JSON netlist: " + path);
794
7
    auto result = JsonReader(input).read();
795
7
    if (input.bad()) throw std::runtime_error("failed reading JSON netlist: " + path);
796
7
    return result;
797
7
}
798
799
}  // namespace labneura::eda