Coverage Report

Created: 2026-11-03 04:34

/home/runner/work/LabNeura/LabNeura/src/labneura/eda/parser/liberty_parser.cpp
Line
Count
Source (jump to first uncovered line)
1
#include "labneura/eda/default_cell_library.h"
2
#include "labneura/eda/cell_library.h"
3
4
#include <cctype>
5
#include <cstdlib>
6
#include <cstring>
7
#include <cmath>
8
#include <fstream>
9
#include <map>
10
#include <sstream>
11
#include <stdexcept>
12
#include <string_view>
13
#include <utility>
14
15
namespace labneura::eda {
16
namespace {
17
18
struct Token {
19
    std::string_view text;
20
    std::size_t start;
21
    std::size_t end;
22
};
23
24
struct Group {
25
    std::string name;
26
    std::vector<std::string> arguments;
27
    std::map<std::string, std::string> attributes;
28
    std::map<std::string, std::vector<std::string>> list_attributes;
29
    std::vector<Group> children;
30
    bool is_attribute = false;
31
};
32
33
1.66M
std::string trim(std::string_view text) {
34
1.66M
    const auto first = text.find_first_not_of(" \t\r\n");
35
1.66M
    if (first == std::string_view::npos) return {};
36
1.66M
    const auto last = text.find_last_not_of(" \t\r\n");
37
1.66M
    return std::string(text.substr(first, last - first + 1));
38
1.66M
}
39
40
711k
std::string decode_value(std::string value) {
41
711k
    value = trim(value);
42
711k
    if (value.size() < 2 || value.front() != '"' || value.back() != '"') {
43
93.5k
        return value;
44
93.5k
    }
45
46
617k
    std::string decoded;
47
617k
    decoded.reserve(value.size() - 2);
48
36.2M
    for (std::size_t i = 1; i + 1 < value.size(); ++i) {
49
35.6M
        if (value[i] == '\\' && i + 2 < value.size()) ++i;
50
35.6M
        decoded.push_back(value[i]);
51
35.6M
    }
52
617k
    return decoded;
53
711k
}
54
55
class LibertyParser {
56
public:
57
17
    explicit LibertyParser(const std::string& source) : source_(source) {
58
17
        tokens_.reserve(source_.size() / 5 + 16);
59
17
        tokenize();
60
17
    }
61
62
17
    std::vector<Group> parse() {
63
17
        std::vector<Group> groups;
64
34
        while (!at_end()) {
65
17
            groups.push_back(parse_statement());
66
17
        }
67
17
        if (groups.empty()) {
68
0
            throw std::runtime_error("Liberty source contains no groups");
69
0
        }
70
17
        return groups;
71
17
    }
72
73
private:
74
    const std::string& source_;
75
    std::vector<Token> tokens_;
76
    std::size_t position_ = 0;
77
78
7.58M
    bool at_end() const noexcept { return position_ == tokens_.size(); }
79
1.77M
    const Token& peek() const {
80
1.77M
        if (at_end()) fail("unexpected end of Liberty source");
81
1.77M
        return tokens_[position_];
82
1.77M
    }
83
688k
    Token take() {
84
688k
        const auto token = peek();
85
688k
        ++position_;
86
688k
        return token;
87
688k
    }
88
2.74M
    bool accept(std::string_view text) {
89
2.74M
        if (!at_end() && tokens_[position_].text == text) {
90
1.26M
            ++position_;
91
1.26M
            return true;
92
1.26M
        }
93
1.48M
        return false;
94
2.74M
    }
95
396k
    void require(std::string_view text) {
96
396k
        if (!accept(text)) fail("expected '" + std::string(text) + "'");
97
396k
    }
98
0
    [[noreturn]] void fail(const std::string& message) const {
99
0
        const auto offset =
100
0
            at_end() ? source_.size() : tokens_[position_].start;
101
0
        throw std::runtime_error("Liberty parse error at byte " +
102
0
                                 std::to_string(offset) + ": " + message);
103
0
    }
104
105
17
    void tokenize() {
106
17
        std::size_t i = 0;
107
26.9M
        while (i < source_.size()) {
108
26.9M
            if (source_[i] == '\\') {
109
340k
                std::size_t continuation_end = i + 1;
110
340k
                while (continuation_end < source_.size() &&
111
340k
                       (source_[continuation_end] == ' ' ||
112
340k
                        source_[continuation_end] == '\t')) {
113
0
                    ++continuation_end;
114
0
                }
115
340k
                if (continuation_end < source_.size() &&
116
340k
                    (source_[continuation_end] == '\n' ||
117
340k
                     source_[continuation_end] == '\r')) {
118
340k
                    i = continuation_end + 1;
119
340k
                    if (source_[continuation_end] == '\r' &&
120
340k
                        i < source_.size() && source_[i] == '\n') {
121
0
                        ++i;
122
0
                    }
123
340k
                    continue;
124
340k
                }
125
340k
            }
126
127
26.5M
            const unsigned char character =
128
26.5M
                static_cast<unsigned char>(source_[i]);
129
26.5M
            if (std::isspace(character)) {
130
22.6M
                ++i;
131
22.6M
                continue;
132
22.6M
            }
133
3.93M
            if (source_[i] == '/' && i + 1 < source_.size() &&
134
3.93M
                source_[i + 1] == '/') {
135
0
                i += 2;
136
0
                while (i < source_.size() && source_[i] != '\n') ++i;
137
0
                continue;
138
0
            }
139
3.93M
            if (source_[i] == '/' && i + 1 < source_.size() &&
140
3.93M
                source_[i + 1] == '*') {
141
9
                const auto comment_start = i;
142
9
                i += 2;
143
1.44k
                while (i + 1 < source_.size() &&
144
1.44k
                       !(source_[i] == '*' && source_[i + 1] == '/')) {
145
1.43k
                    ++i;
146
1.43k
                }
147
9
                if (i + 1 >= source_.size()) {
148
0
                    throw std::runtime_error(
149
0
                        "Liberty parse error at byte " +
150
0
                        std::to_string(comment_start) +
151
0
                        ": unterminated block comment");
152
0
                }
153
9
                i += 2;
154
9
                continue;
155
9
            }
156
157
3.93M
            const auto start = i;
158
3.93M
            if (source_[i] == '"') {
159
861k
                ++i;
160
861k
                bool closed = false;
161
55.6M
                while (i < source_.size()) {
162
55.6M
                    if (source_[i] == '\\' && i + 1 < source_.size()) {
163
0
                        i += 2;
164
55.6M
                    } else if (source_[i++] == '"') {
165
861k
                        closed = true;
166
861k
                        break;
167
861k
                    }
168
55.6M
                }
169
861k
                if (!closed) {
170
0
                    throw std::runtime_error(
171
0
                        "Liberty parse error at byte " +
172
0
                        std::to_string(start) + ": unterminated string");
173
0
                }
174
3.07M
            } else if (std::string_view("(){}:;,").find(source_[i]) !=
175
3.07M
                       std::string_view::npos) {
176
2.29M
                ++i;
177
2.29M
            } else {
178
8.27M
                while (i < source_.size() &&
179
8.27M
                       !std::isspace(static_cast<unsigned char>(source_[i])) &&
180
8.27M
                       std::string_view("(){}:;,\"").find(source_[i]) ==
181
7.80M
                           std::string_view::npos) {
182
7.49M
                    if (source_[i] == '/' && i + 1 < source_.size() &&
183
7.49M
                        (source_[i + 1] == '/' || source_[i + 1] == '*')) {
184
0
                        break;
185
0
                    }
186
7.49M
                    ++i;
187
7.49M
                }
188
782k
                if (i == start) ++i;
189
782k
            }
190
3.93M
            tokens_.push_back(
191
3.93M
                {std::string_view(source_).substr(start, i - start), start, i});
192
3.93M
        }
193
17
    }
194
195
955k
    std::string token_slice(std::size_t begin, std::size_t end) const {
196
955k
        if (begin >= end) return {};
197
955k
        return trim(std::string_view(source_).substr(
198
955k
            tokens_[begin].start, tokens_[end - 1].end - tokens_[begin].start));
199
955k
    }
200
201
396k
    std::vector<std::string> parse_arguments() {
202
396k
        require("(");
203
396k
        std::vector<std::string> arguments;
204
396k
        std::size_t item_start = position_;
205
396k
        std::size_t nesting = 0;
206
1.40M
        while (!at_end()) {
207
1.40M
            if (tokens_[position_].text == "(") {
208
0
                ++nesting;
209
0
                ++position_;
210
1.40M
            } else if (tokens_[position_].text == ")") {
211
396k
                if (nesting == 0) {
212
396k
                    if (item_start != position_) {
213
322k
                        arguments.push_back(token_slice(item_start, position_));
214
322k
                    } else if (!arguments.empty()) {
215
0
                        fail("empty Liberty group argument");
216
0
                    }
217
396k
                    ++position_;
218
396k
                    return arguments;
219
396k
                }
220
0
                --nesting;
221
0
                ++position_;
222
1.00M
            } else if (tokens_[position_].text == "," && nesting == 0) {
223
341k
                if (item_start == position_) fail("empty Liberty group argument");
224
341k
                arguments.push_back(token_slice(item_start, position_));
225
341k
                ++position_;
226
341k
                item_start = position_;
227
663k
            } else {
228
663k
                ++position_;
229
663k
            }
230
1.40M
        }
231
0
        fail("unterminated parenthesized argument list");
232
0
    }
233
234
291k
    std::string parse_scalar() {
235
291k
        const auto start = position_;
236
291k
        std::size_t nesting = 0;
237
583k
        while (!at_end()) {
238
583k
            if (tokens_[position_].text == "(") {
239
0
                ++nesting;
240
0
                ++position_;
241
583k
            } else if (tokens_[position_].text == ")") {
242
0
                if (nesting == 0) fail("unexpected ')' in Liberty attribute");
243
0
                --nesting;
244
0
                ++position_;
245
583k
            } else if (tokens_[position_].text == ";" && nesting == 0) {
246
291k
                const auto value = decode_value(token_slice(start, position_));
247
291k
                ++position_;
248
291k
                return value;
249
291k
            } else {
250
291k
                ++position_;
251
291k
            }
252
583k
        }
253
0
        fail("unterminated Liberty attribute");
254
0
    }
255
256
688k
    Group parse_statement() {
257
688k
        if (peek().text == "}") fail("unexpected closing brace");
258
688k
        Group result;
259
688k
        result.name = std::string(take().text);
260
261
688k
        if (accept(":")) {
262
291k
            result.attributes.emplace(result.name, parse_scalar());
263
291k
            result.is_attribute = true;
264
291k
            return result;
265
291k
        }
266
267
396k
        if (!at_end() && peek().text == "(") {
268
396k
            result.arguments = parse_arguments();
269
396k
        }
270
271
396k
        if (accept("{")) {
272
869k
            while (!accept("}")) {
273
688k
                if (at_end()) fail("unterminated Liberty group");
274
688k
                auto child = parse_statement();
275
688k
                if (child.is_attribute && !child.attributes.empty()) {
276
291k
                    for (auto& [key, value] : child.attributes) {
277
291k
                        result.attributes[key] = std::move(value);
278
291k
                    }
279
396k
                } else if (child.is_attribute &&
280
396k
                           !child.list_attributes.empty()) {
281
215k
                    for (auto& [key, values] : child.list_attributes) {
282
215k
                        result.list_attributes[key] = std::move(values);
283
215k
                    }
284
215k
                } else {
285
181k
                    result.children.push_back(std::move(child));
286
181k
                }
287
688k
            }
288
181k
            accept(";");
289
181k
            return result;
290
181k
        }
291
292
215k
        if (accept(";")) {
293
215k
            if (!result.arguments.empty()) {
294
215k
                result.list_attributes.emplace(result.name,
295
215k
                                               std::move(result.arguments));
296
215k
                result.is_attribute = true;
297
215k
            }
298
215k
            return result;
299
215k
        }
300
0
        fail("expected group body or ';'");
301
0
    }
302
};
303
304
std::string attribute(const Group& group, std::string_view key,
305
63.7k
                      std::string default_value = {}) {
306
63.7k
    const auto it = group.attributes.find(std::string(key));
307
63.7k
    return it == group.attributes.end() ? std::move(default_value) : it->second;
308
63.7k
}
309
310
std::optional<double> numeric_attribute(const Group& group,
311
15.5k
                                        std::string_view key) {
312
15.5k
    const auto value = group.attributes.find(std::string(key));
313
15.5k
    if (value == group.attributes.end()) return std::nullopt;
314
12.3k
    try {
315
12.3k
        std::size_t consumed = 0;
316
12.3k
        const auto parsed = std::stod(value->second, &consumed);
317
12.3k
        if (consumed != value->second.size() || !std::isfinite(parsed)) {
318
0
            throw std::invalid_argument("not a finite number");
319
0
        }
320
12.3k
        return parsed;
321
12.3k
    } catch (const std::exception&) {
322
0
        throw std::runtime_error("invalid numeric Liberty attribute '" +
323
0
                                 std::string(key) + "': " + value->second);
324
0
    }
325
12.3k
}
326
327
// Appends every comma-separated number in `text`, rejecting any item that is
328
// not entirely a finite number.
329
void append_numbers(const std::string& text, std::string_view key,
330
360k
                    std::vector<double>& out) {
331
360k
    const char* cursor = text.c_str();
332
360k
    const char* const end = cursor + text.size();
333
6.92M
    const auto is_blank = [](char c) {
334
6.92M
        return c == ' ' || c == '\t' || c == '\r' || c == '\n';
335
6.92M
    };
336
2.78M
    while (cursor < end) {
337
2.42M
        const char* item_end = static_cast<const char*>(
338
2.42M
            std::memchr(cursor, ',', static_cast<std::size_t>(end - cursor)));
339
2.42M
        if (!item_end) item_end = end;
340
2.42M
        const char* first = cursor;
341
2.42M
        const char* last = item_end;
342
4.49M
        while (first < last && is_blank(*first)) ++first;
343
2.42M
        while (last > first && is_blank(last[-1])) --last;
344
2.42M
        if (first != last) {
345
2.42M
            char* parsed_end = nullptr;
346
2.42M
            const double value = std::strtod(first, &parsed_end);
347
2.42M
            if (parsed_end != last || !std::isfinite(value)) {
348
0
                throw std::runtime_error("invalid numeric value in Liberty '" +
349
0
                                         std::string(key) + "': " +
350
0
                                         std::string(first, last));
351
0
            }
352
2.42M
            out.push_back(value);
353
2.42M
        }
354
2.42M
        cursor = item_end + 1;
355
2.42M
    }
356
360k
}
357
358
std::vector<double> numeric_values(const Group& group,
359
86.2k
                                   std::string_view key) {
360
86.2k
    std::vector<double> result;
361
86.2k
    const auto found = group.list_attributes.find(std::string(key));
362
86.2k
    if (found == group.list_attributes.end()) return result;
363
84.6k
    for (const auto& argument : found->second) {
364
84.6k
        append_numbers(decode_value(argument), key, result);
365
84.6k
    }
366
84.6k
    return result;
367
86.2k
}
368
369
std::map<std::string, std::vector<double>> collect_templates(
370
17
    const Group& library) {
371
17
    std::map<std::string, std::vector<double>> templates;
372
3.11k
    for (const auto& child : library.children) {
373
3.11k
        if (child.name != "lu_table_template" || child.arguments.empty()) continue;
374
33
        templates[decode_value(child.arguments.front())] =
375
33
            numeric_values(child, "index_1");
376
33
        templates[decode_value(child.arguments.front()) + "#2"] =
377
33
            numeric_values(child, "index_2");
378
33
    }
379
17
    return templates;
380
17
}
381
382
std::optional<LookupTable> parse_table(
383
    const Group& group,
384
43.0k
    const std::map<std::string, std::vector<double>>& templates) {
385
43.0k
    const auto found = group.list_attributes.find("values");
386
43.0k
    if (found == group.list_attributes.end()) return std::nullopt;
387
388
43.0k
    std::vector<std::vector<double>> values;
389
43.0k
    values.reserve(found->second.size());
390
43.0k
    bool has_values = false;
391
276k
    for (const auto& raw_row : found->second) {
392
276k
        std::vector<double> row;
393
276k
        append_numbers(decode_value(raw_row), "values", row);
394
276k
        has_values = has_values || !row.empty();
395
276k
        values.push_back(std::move(row));
396
276k
    }
397
43.0k
    if (!has_values) return std::nullopt;
398
399
43.0k
    std::vector<double> index_1 = numeric_values(group, "index_1");
400
43.0k
    std::vector<double> index_2 = numeric_values(group, "index_2");
401
43.0k
    const std::string template_name =
402
43.0k
        group.arguments.empty() ? "" : decode_value(group.arguments.front());
403
43.0k
    if (index_1.empty()) {
404
244
        const auto it = templates.find(template_name);
405
244
        if (it != templates.end()) index_1 = it->second;
406
244
    }
407
43.0k
    if (index_2.empty()) {
408
1.35k
        const auto it = templates.find(template_name + "#2");
409
1.35k
        if (it != templates.end()) index_2 = it->second;
410
1.35k
    }
411
43.0k
    if (!index_1.empty() && !index_2.empty()) {
412
41.7k
        if (values.size() != index_1.size()) {
413
0
            throw std::runtime_error(
414
0
                "Liberty timing table row count does not match index_1");
415
0
        }
416
274k
        for (const auto& row : values) {
417
274k
            if (row.size() != index_2.size()) {
418
0
                throw std::runtime_error(
419
0
                    "Liberty timing table column count does not match index_2");
420
0
            }
421
274k
        }
422
41.7k
    }
423
43.0k
    return LookupTable(template_name, std::move(index_1), std::move(index_2),
424
43.0k
                       std::move(values));
425
43.0k
}
426
427
TimingArc parse_timing(
428
    const Group& group,
429
12.9k
    const std::map<std::string, std::vector<double>>& templates) {
430
12.9k
    std::optional<LookupTable> cell_rise;
431
12.9k
    std::optional<LookupTable> cell_fall;
432
12.9k
    std::optional<LookupTable> rise_transition;
433
12.9k
    std::optional<LookupTable> fall_transition;
434
12.9k
    std::optional<LookupTable> rise_constraint;
435
12.9k
    std::optional<LookupTable> fall_constraint;
436
43.0k
    for (const auto& child : group.children) {
437
43.0k
        if (child.name == "cell_rise") {
438
9.41k
            cell_rise = parse_table(child, templates);
439
33.6k
        } else if (child.name == "cell_fall") {
440
9.42k
            cell_fall = parse_table(child, templates);
441
24.2k
        } else if (child.name == "rise_transition") {
442
9.38k
            rise_transition = parse_table(child, templates);
443
14.8k
        } else if (child.name == "fall_transition") {
444
9.40k
            fall_transition = parse_table(child, templates);
445
9.40k
        } else if (child.name == "rise_constraint") {
446
2.94k
            rise_constraint = parse_table(child, templates);
447
2.94k
        } else if (child.name == "fall_constraint") {
448
2.51k
            fall_constraint = parse_table(child, templates);
449
2.51k
        }
450
43.0k
    }
451
12.9k
    return TimingArc(attribute(group, "related_pin"),
452
12.9k
                     attribute(group, "timing_type"),
453
12.9k
                     attribute(group, "timing_sense"),
454
12.9k
                     std::move(cell_rise), std::move(cell_fall),
455
12.9k
                     std::move(rise_transition), std::move(fall_transition),
456
12.9k
                     std::move(rise_constraint), std::move(fall_constraint));
457
12.9k
}
458
459
CellPin parse_pin(const Group& group,
460
12.4k
                  const std::map<std::string, std::vector<double>>& templates) {
461
12.4k
    if (group.arguments.empty()) {
462
0
        throw std::runtime_error("Liberty pin group is missing its name");
463
0
    }
464
12.4k
    std::vector<TimingArc> timing_arcs;
465
30.2k
    for (const auto& child : group.children) {
466
30.2k
        if (child.name == "timing") {
467
12.9k
            timing_arcs.push_back(parse_timing(child, templates));
468
12.9k
        }
469
30.2k
    }
470
12.4k
    return CellPin(decode_value(group.arguments.front()),
471
12.4k
                   attribute(group, "direction"),
472
12.4k
                   attribute(group, "function"),
473
12.4k
                   numeric_attribute(group, "capacitance"),
474
12.4k
                   std::move(timing_arcs));
475
12.4k
}
476
477
StandardCell parse_cell(
478
    const Group& group,
479
3.02k
    const std::map<std::string, std::vector<double>>& templates) {
480
3.02k
    if (group.arguments.empty()) {
481
0
        throw std::runtime_error("Liberty cell group is missing its name");
482
0
    }
483
3.02k
    std::vector<CellPin> pins;
484
68.9k
    for (const auto& child : group.children) {
485
68.9k
        if (child.name == "pin") pins.push_back(parse_pin(child, templates));
486
68.9k
    }
487
3.02k
    return StandardCell(decode_value(group.arguments.front()),
488
3.02k
                        numeric_attribute(group, "area"), std::move(pins));
489
3.02k
}
490
491
17
StandardCellLibrary parse_library(const std::string& source) {
492
17
    const auto roots = LibertyParser(source).parse();
493
17
    const Group* library = nullptr;
494
17
    for (const auto& root : roots) {
495
17
        if (root.name == "library") {
496
17
            if (library) {
497
0
                throw std::runtime_error(
498
0
                    "Liberty source contains more than one library group");
499
0
            }
500
17
            library = &root;
501
17
        }
502
17
    }
503
17
    if (!library || library->arguments.empty()) {
504
0
        throw std::runtime_error(
505
0
            "Liberty source must contain a named library group");
506
0
    }
507
508
17
    const auto templates = collect_templates(*library);
509
17
    std::vector<StandardCell> cells;
510
3.11k
    for (const auto& child : library->children) {
511
3.11k
        if (child.name == "cell") cells.push_back(parse_cell(child, templates));
512
3.11k
    }
513
17
    if (cells.empty()) {
514
1
        throw std::runtime_error("Liberty library contains no cell groups");
515
1
    }
516
16
    std::string capacitance_unit = attribute(*library, "capacitive_load_unit");
517
16
    const auto unit = library->list_attributes.find("capacitive_load_unit");
518
16
    if (unit != library->list_attributes.end()) {
519
14
        std::ostringstream formatted;
520
42
        for (std::size_t i = 0; i < unit->second.size(); ++i) {
521
28
            if (i != 0) formatted << ", ";
522
28
            formatted << decode_value(unit->second[i]);
523
28
        }
524
14
        capacitance_unit = formatted.str();
525
14
    }
526
16
    return StandardCellLibrary(decode_value(library->arguments.front()),
527
16
                               attribute(*library, "time_unit"),
528
16
                               std::move(capacitance_unit), std::move(cells));
529
17
}
530
531
}  // namespace
532
533
17
StandardCellLibrary parse_liberty(const std::string& path) {
534
17
    std::ifstream input(path, std::ios::binary | std::ios::ate);
535
17
    if (!input) {
536
0
        throw std::runtime_error("could not open Liberty file: " + path);
537
0
    }
538
17
    const auto size = input.tellg();
539
17
    std::string source;
540
17
    if (size > 0) {
541
17
        source.resize(static_cast<std::size_t>(size));
542
17
        input.seekg(0);
543
17
        input.read(source.data(), size);
544
17
    }
545
17
    if (input.bad() || (size > 0 && input.gcount() != size)) {
546
0
        throw std::runtime_error("failed reading Liberty file: " + path);
547
0
    }
548
17
    return parse_library(source);
549
17
}
550
551
0
const StandardCellLibrary& get_default_cell_library() {
552
0
    static const StandardCellLibrary library =
553
0
        parse_library(detail::get_bundled_liberty());
554
0
    return library;
555
0
}
556
557
}  // namespace labneura::eda