Coverage Report

Created: 2026-11-07 16:24

/home/runner/work/LabNeura/LabNeura/src/labneura/eda/parser/verilog_parser.cpp
Line
Count
Source (jump to first uncovered line)
1
#include "labneura/eda/netlist.h"
2
#include "labneura/eda/parsed_verilog_context.h"
3
4
#include "slang/ast/ASTSerializer.h"
5
#include "slang/ast/Compilation.h"
6
#include "slang/ast/expressions/AssignmentExpressions.h"
7
#include "slang/ast/expressions/ConversionExpression.h"
8
#include "slang/ast/expressions/LiteralExpressions.h"
9
#include "slang/ast/expressions/MiscExpressions.h"
10
#include "slang/ast/expressions/OperatorExpressions.h"
11
#include "slang/ast/expressions/SelectExpressions.h"
12
#include "slang/ast/symbols/CompilationUnitSymbols.h"
13
#include "slang/ast/symbols/BlockSymbols.h"
14
#include "slang/ast/symbols/InstanceSymbols.h"
15
#include "slang/ast/symbols/MemberSymbols.h"
16
#include "slang/ast/symbols/PortSymbols.h"
17
#include "slang/ast/types/Type.h"
18
#include "slang/diagnostics/TextDiagnosticClient.h"
19
#include "slang/driver/Driver.h"
20
#include "slang/ast/SemanticFacts.h"
21
#include "slang/syntax/SyntaxTree.h"
22
#include "slang/text/Json.h"
23
#include "slang/text/SourceManager.h"
24
25
#include <algorithm>
26
#include <cstddef>
27
#include <filesystem>
28
#include <fstream>
29
#include <stdexcept>
30
#include <string_view>
31
#include <unordered_set>
32
#include <utility>
33
#include <vector>
34
35
namespace labneura::eda {
36
namespace {
37
38
std::shared_ptr<detail::ParsedVerilogContext> parse_sources(
39
196
    std::vector<std::string>& arguments, const std::string& context_name) {
40
196
    auto context = std::make_shared<detail::ParsedVerilogContext>();
41
196
    auto& driver = context->driver;
42
196
    driver.addStandardArgs();
43
196
    std::vector<char*> argv;
44
196
    argv.reserve(arguments.size());
45
896
    for (auto& argument : arguments) argv.push_back(argument.data());
46
47
196
    if (!driver.parseCommandLine(static_cast<int>(argv.size()), argv.data())) {
48
0
        (void)driver.reportDiagnostics(false);
49
0
        throw std::runtime_error("slang could not parse the " + context_name +
50
0
                                 " options");
51
0
    }
52
196
    if (!driver.processOptions()) {
53
0
        (void)driver.reportDiagnostics(false);
54
0
        throw std::runtime_error("slang failed to process the " + context_name +
55
0
                                 " options");
56
0
    }
57
196
    const bool parsed_sources = driver.parseAllSources();
58
196
    const bool parse_diagnostics_ok = driver.reportParseDiags();
59
196
    if (!parsed_sources || !parse_diagnostics_ok) {
60
1
        throw std::runtime_error("slang failed to parse the " + context_name);
61
1
    }
62
63
195
    context->compilation = driver.createCompilation();
64
195
    driver.reportCompilation(*context->compilation, true);
65
195
    if (!driver.reportDiagnostics(true)) {
66
1
        throw std::runtime_error("slang failed to compile the " + context_name +
67
1
                                 ":\n" + driver.textDiagClient->getString());
68
1
    }
69
194
    return context;
70
195
}
71
72
345
bool is_systemverilog(const std::filesystem::path& path) {
73
345
    return path.extension() == ".sv";
74
345
}
75
76
std::pair<std::optional<std::int64_t>, std::optional<std::int64_t>>
77
7.98k
declared_bounds(const slang::ast::Type& type) {
78
7.98k
    if (!type.isPackedArray()) return {};
79
2.17k
    const auto range = type.getFixedRange();
80
2.17k
    if (range.width() != static_cast<std::size_t>(type.getBitWidth())) {
81
10
        const auto width = static_cast<std::int64_t>(type.getBitWidth());
82
10
        return {width - 1, 0};
83
10
    }
84
2.16k
    return {range.left, range.right};
85
2.17k
}
86
87
struct DeclaredShape {
88
    std::size_t width = 1;
89
    std::size_t packed_width = 1;
90
    std::optional<std::int64_t> packed_left;
91
    std::optional<std::int64_t> packed_right;
92
    std::optional<std::int64_t> unpacked_left;
93
    std::optional<std::int64_t> unpacked_right;
94
};
95
96
7.98k
DeclaredShape declared_shape(const slang::ast::Type& type) {
97
7.98k
    DeclaredShape shape;
98
7.98k
    if (type.isUnpackedArray()) {
99
108
        if (!type.hasFixedRange() || !type.getArrayElementType()) {
100
0
            throw std::runtime_error(
101
0
                "netlist I/O requires fixed-size unpacked arrays");
102
0
        }
103
108
        const auto* element = type.getArrayElementType();
104
108
        if (element->isUnpackedArray()) {
105
0
            throw std::runtime_error(
106
0
                "netlist I/O currently supports one unpacked array dimension");
107
0
        }
108
108
        const auto array_range = type.getFixedRange();
109
108
        shape.packed_width = static_cast<std::size_t>(element->getBitWidth());
110
108
        shape.width = array_range.width() * shape.packed_width;
111
108
        const auto [left, right] = declared_bounds(*element);
112
108
        shape.packed_left = left;
113
108
        shape.packed_right = right;
114
108
        shape.unpacked_left = array_range.left;
115
108
        shape.unpacked_right = array_range.right;
116
7.87k
    } else {
117
7.87k
        shape.width = static_cast<std::size_t>(type.getBitWidth());
118
7.87k
        shape.packed_width = shape.width;
119
7.87k
        const auto [left, right] = declared_bounds(type);
120
7.87k
        shape.packed_left = left;
121
7.87k
        shape.packed_right = right;
122
7.87k
    }
123
7.98k
    return shape;
124
7.98k
}
125
126
void collect_constant_selects(
127
    const slang::ast::Expression& expression,
128
    const slang::SourceManager& source_manager,
129
    const slang::BufferID source_buffer, std::size_t source_offset,
130
    const std::string& scope_prefix,
131
    std::vector<std::pair<std::size_t, std::pair<std::size_t, std::string>>>&
132
51.5k
        replacements) {
133
51.5k
    using slang::ast::ExpressionKind;
134
51.5k
    const auto replace_source = [&](const slang::ast::Expression& source,
135
51.5k
                                    const std::string& value) {
136
3.49k
        const auto range = source_manager.getFullyOriginalRange(source.sourceRange);
137
3.49k
        const auto start = range.start();
138
3.49k
        const auto end = range.end();
139
3.49k
        if (!start.valid() || !end.valid() ||
140
3.49k
            start.buffer() != source_buffer || end.buffer() != source_buffer ||
141
3.49k
            end.offset() < start.offset()) {
142
0
            return;
143
0
        }
144
3.49k
        replacements.push_back(
145
3.49k
            {start.offset() - source_offset,
146
3.49k
             {end.offset() - source_offset, value}});
147
3.49k
    };
148
51.5k
    const auto replace_constant = [&](const slang::ast::Expression& selector) {
149
3.50k
        const auto range =
150
3.50k
            source_manager.getFullyOriginalRange(selector.sourceRange);
151
3.50k
        const auto start = range.start();
152
3.50k
        const auto end = range.end();
153
3.50k
        const auto* constant = selector.getConstant();
154
3.50k
        if (!start.valid() || !end.valid() || start.buffer() != source_buffer ||
155
3.50k
            end.buffer() != source_buffer || end.offset() < start.offset() ||
156
3.50k
            !constant || !constant->isInteger()) {
157
12
            return false;
158
12
        }
159
3.49k
        const auto value = constant->integer().as<std::int64_t>();
160
3.49k
        if (!value) return false;
161
3.49k
        replace_source(selector, std::to_string(*value));
162
3.49k
        return true;
163
3.49k
    };
164
165
51.5k
    switch (expression.kind) {
166
27.9k
        case ExpressionKind::NamedValue:
167
28.1k
        case ExpressionKind::HierarchicalValue: {
168
28.1k
            const auto& symbol =
169
28.1k
                expression.as<slang::ast::ValueExpressionBase>().symbol;
170
28.1k
            if (scope_prefix.empty() ||
171
28.1k
                symbol.kind == slang::ast::SymbolKind::Parameter ||
172
28.1k
                symbol.kind == slang::ast::SymbolKind::EnumValue) {
173
25.5k
                return;
174
25.5k
            }
175
2.53k
            std::string path = symbol.getHierarchicalPath();
176
2.53k
            if (path.rfind(scope_prefix, 0) == 0) {
177
2.53k
                path.erase(0, scope_prefix.size());
178
2.53k
                if (path != symbol.name) replace_source(expression, path);
179
2.53k
            }
180
2.53k
            return;
181
28.1k
        }
182
2.19k
        case ExpressionKind::ElementSelect: {
183
2.19k
            const auto& select =
184
2.19k
                expression.as<slang::ast::ElementSelectExpression>();
185
2.19k
            collect_constant_selects(select.value(), source_manager,
186
2.19k
                                     source_buffer, source_offset, scope_prefix,
187
2.19k
                                     replacements);
188
2.19k
            if (!replace_constant(select.selector())) {
189
12
                collect_constant_selects(select.selector(), source_manager,
190
12
                                         source_buffer, source_offset, scope_prefix,
191
12
                                         replacements);
192
12
            }
193
2.19k
            return;
194
28.1k
        }
195
655
        case ExpressionKind::RangeSelect: {
196
655
            const auto& select =
197
655
                expression.as<slang::ast::RangeSelectExpression>();
198
655
            collect_constant_selects(select.value(), source_manager,
199
655
                                     source_buffer, source_offset, scope_prefix,
200
655
                                     replacements);
201
655
            if (!replace_constant(select.left())) {
202
0
                collect_constant_selects(select.left(), source_manager,
203
0
                                         source_buffer, source_offset, scope_prefix,
204
0
                                         replacements);
205
0
            }
206
655
            if (!replace_constant(select.right())) {
207
0
                collect_constant_selects(select.right(), source_manager,
208
0
                                         source_buffer, source_offset, scope_prefix,
209
0
                                         replacements);
210
0
            }
211
655
            return;
212
28.1k
        }
213
494
        case ExpressionKind::MemberAccess:
214
494
            collect_constant_selects(
215
494
                expression.as<slang::ast::MemberAccessExpression>().value(),
216
494
                source_manager, source_buffer, source_offset, scope_prefix,
217
494
                replacements);
218
494
            return;
219
2.73k
        case ExpressionKind::UnaryOp:
220
2.73k
            collect_constant_selects(
221
2.73k
                expression.as<slang::ast::UnaryExpression>().operand(),
222
2.73k
                source_manager, source_buffer, source_offset, scope_prefix,
223
2.73k
                replacements);
224
2.73k
            return;
225
8.37k
        case ExpressionKind::BinaryOp: {
226
8.37k
            const auto& binary =
227
8.37k
                expression.as<slang::ast::BinaryExpression>();
228
8.37k
            collect_constant_selects(binary.left(), source_manager,
229
8.37k
                                     source_buffer, source_offset, scope_prefix,
230
8.37k
                                     replacements);
231
8.37k
            collect_constant_selects(binary.right(), source_manager,
232
8.37k
                                     source_buffer, source_offset, scope_prefix,
233
8.37k
                                     replacements);
234
8.37k
            return;
235
28.1k
        }
236
445
        case ExpressionKind::ConditionalOp: {
237
445
            const auto& conditional =
238
445
                expression.as<slang::ast::ConditionalExpression>();
239
445
            for (const auto& condition : conditional.conditions) {
240
445
                collect_constant_selects(*condition.expr, source_manager,
241
445
                                         source_buffer, source_offset, scope_prefix,
242
445
                                         replacements);
243
445
            }
244
445
            collect_constant_selects(conditional.left(), source_manager,
245
445
                                     source_buffer, source_offset, scope_prefix,
246
445
                                     replacements);
247
445
            collect_constant_selects(conditional.right(), source_manager,
248
445
                                     source_buffer, source_offset, scope_prefix,
249
445
                                     replacements);
250
445
            return;
251
28.1k
        }
252
368
        case ExpressionKind::Concatenation:
253
368
            for (const auto* operand :
254
368
                 expression.as<slang::ast::ConcatenationExpression>()
255
888
                     .operands()) {
256
888
                collect_constant_selects(*operand, source_manager,
257
888
                                         source_buffer, source_offset, scope_prefix,
258
888
                                         replacements);
259
888
            }
260
368
            return;
261
1.73k
        case ExpressionKind::Conversion:
262
1.73k
            collect_constant_selects(
263
1.73k
                expression.as<slang::ast::ConversionExpression>().operand(),
264
1.73k
                source_manager, source_buffer, source_offset, scope_prefix,
265
1.73k
                replacements);
266
1.73k
            return;
267
6.43k
        default:
268
6.43k
            return;
269
51.5k
    }
270
51.5k
}
271
272
53.3k
std::string trim(const std::string& text) {
273
53.3k
    const auto first = text.find_first_not_of(" \t\r\n");
274
53.3k
    if (first == std::string::npos) return {};
275
53.3k
    const auto last = text.find_last_not_of(" \t\r\n");
276
53.3k
    return text.substr(first, last - first + 1);
277
53.3k
}
278
279
std::string source_range_text(const slang::SourceRange& macro_range,
280
28.5k
                              const slang::SourceManager& source_manager) {
281
28.5k
    const auto range = source_manager.getFullyOriginalRange(macro_range);
282
28.5k
    const auto start = range.start();
283
28.5k
    const auto end = range.end();
284
28.5k
    if (!start.valid() || !end.valid() || start.buffer() != end.buffer() ||
285
28.5k
        end.offset() < start.offset()) {
286
0
        throw std::runtime_error(
287
0
            "could not determine source text for Verilog assignment expression");
288
0
    }
289
290
28.5k
    const auto source = source_manager.getSourceText(start.buffer());
291
28.5k
    if (end.offset() > source.size()) {
292
0
        throw std::runtime_error(
293
0
            "Verilog assignment expression source range is out of bounds");
294
0
    }
295
28.5k
    return trim(std::string(source.substr(start.offset(),
296
28.5k
                                          end.offset() - start.offset())));
297
28.5k
}
298
299
std::string expression_source(const slang::ast::Expression& expression,
300
                              const slang::SourceManager& source_manager,
301
24.7k
                              const std::string& scope_prefix = {}) {
302
24.7k
    auto source = source_range_text(expression.sourceRange, source_manager);
303
24.7k
    const auto range =
304
24.7k
        source_manager.getFullyOriginalRange(expression.sourceRange);
305
24.7k
    const auto start = range.start();
306
24.7k
    const auto end = range.end();
307
24.7k
    if (!start.valid() || !end.valid() || start.buffer() != end.buffer() ||
308
24.7k
        end.offset() < start.offset()) {
309
0
        return source;
310
0
    }
311
24.7k
    std::vector<std::pair<
312
24.7k
        std::size_t, std::pair<std::size_t, std::string>>> replacements;
313
24.7k
    collect_constant_selects(expression, source_manager, start.buffer(),
314
24.7k
                             start.offset(), scope_prefix, replacements);
315
24.7k
    std::sort(replacements.rbegin(), replacements.rend());
316
24.7k
    for (const auto& [begin, replacement] : replacements) {
317
3.49k
        const auto& [finish, value] = replacement;
318
3.49k
        if (finish <= source.size() && begin <= finish) {
319
3.49k
            source.replace(begin, finish - begin, value);
320
3.49k
        }
321
3.49k
    }
322
24.7k
    return trim(source);
323
24.7k
}
324
325
std::vector<PinConnection> module_port_connections(
326
    const slang::ast::InstanceSymbol& instance,
327
    const slang::SourceManager& source_manager,
328
244
    const std::string& scope_prefix) {
329
244
    std::vector<PinConnection> connections;
330
3.29k
    for (const auto* connection : instance.getPortConnections()) {
331
3.29k
        if (!connection->getExpression()) continue;
332
3.24k
        connections.emplace_back(
333
3.24k
            std::string(connection->port.name),
334
3.24k
            expression_source(*connection->getExpression(), source_manager,
335
3.24k
                              scope_prefix));
336
3.24k
    }
337
244
    return connections;
338
244
}
339
340
std::vector<PinConnection> parsed_primitive_connections(
341
    const slang::ast::PrimitiveInstanceSymbol& instance,
342
    const slang::SourceManager& source_manager,
343
70
    const std::string& scope_prefix) {
344
70
    const auto expressions = instance.getPortConnections();
345
70
    if (expressions.empty()) return {};
346
347
70
    std::vector<PinConnection> connections;
348
70
    connections.reserve(expressions.size());
349
70
    connections.emplace_back(
350
70
        "Y", expression_source(*expressions.front(), source_manager,
351
70
                               scope_prefix));
352
208
    for (std::size_t i = 1; i < expressions.size(); ++i) {
353
138
        const auto input_name =
354
138
            i <= 26 ? std::string(1, static_cast<char>('A' + i - 1))
355
138
                    : "IN" + std::to_string(i);
356
138
        connections.emplace_back(
357
138
            input_name,
358
138
            expression_source(*expressions[i], source_manager, scope_prefix));
359
138
    }
360
70
    return connections;
361
70
}
362
363
Expression lower_expression(const slang::ast::Expression& expression,
364
20.2k
                            const slang::SourceManager& source_manager) {
365
20.2k
    using slang::ast::ExpressionKind;
366
20.2k
    const std::string source = expression_source(expression, source_manager);
367
20.2k
    switch (expression.kind) {
368
10.5k
        case ExpressionKind::NamedValue: {
369
10.5k
            const auto& named = expression.as<slang::ast::NamedValueExpression>();
370
10.5k
            return {labneura::eda::ExpressionKind::Identifier,
371
10.5k
                    std::string(named.symbol.name), source, {},
372
10.5k
                    expression.type->getBitWidth()};
373
0
        }
374
1.84k
        case ExpressionKind::IntegerLiteral:
375
1.84k
        case ExpressionKind::RealLiteral:
376
1.84k
        case ExpressionKind::TimeLiteral:
377
2.22k
        case ExpressionKind::UnbasedUnsizedIntegerLiteral:
378
2.22k
        case ExpressionKind::NullLiteral:
379
2.22k
        case ExpressionKind::StringLiteral:
380
2.22k
            return {labneura::eda::ExpressionKind::Literal, source, source, {},
381
2.22k
                    expression.type->getBitWidth()};
382
1.32k
        case ExpressionKind::ElementSelect: {
383
1.32k
            const auto& select =
384
1.32k
                expression.as<slang::ast::ElementSelectExpression>();
385
1.32k
            return {labneura::eda::ExpressionKind::BitSelect, "", source,
386
1.32k
                    {lower_expression(select.value(), source_manager),
387
1.32k
                     lower_expression(select.selector(), source_manager)},
388
1.32k
                    expression.type->getBitWidth()};
389
2.22k
        }
390
305
        case ExpressionKind::RangeSelect: {
391
305
            const auto& select =
392
305
                expression.as<slang::ast::RangeSelectExpression>();
393
305
            return {labneura::eda::ExpressionKind::RangeSelect, "", source,
394
305
                    {lower_expression(select.value(), source_manager),
395
305
                     lower_expression(select.left(), source_manager),
396
305
                    lower_expression(select.right(), source_manager)},
397
305
                    expression.type->getBitWidth()};
398
2.22k
        }
399
719
        case ExpressionKind::UnaryOp: {
400
719
            const auto& unary = expression.as<slang::ast::UnaryExpression>();
401
719
            return {labneura::eda::ExpressionKind::Unary,
402
719
                    source_range_text(unary.opRange, source_manager), source,
403
719
                    {lower_expression(unary.operand(), source_manager)},
404
719
                    expression.type->getBitWidth()};
405
2.22k
        }
406
3.10k
        case ExpressionKind::BinaryOp: {
407
3.10k
            const auto& binary = expression.as<slang::ast::BinaryExpression>();
408
3.10k
            const auto operator_text =
409
3.10k
                source_range_text(binary.opRange, source_manager);
410
3.10k
            return {labneura::eda::ExpressionKind::Binary, operator_text, source,
411
3.10k
                    {lower_expression(binary.left(), source_manager),
412
3.10k
                     lower_expression(binary.right(), source_manager)},
413
3.10k
                    expression.type->getBitWidth()};
414
2.22k
        }
415
356
        case ExpressionKind::ConditionalOp: {
416
356
            const auto& conditional =
417
356
                expression.as<slang::ast::ConditionalExpression>();
418
356
            std::vector<labneura::eda::Expression> operands;
419
356
            for (const auto& condition : conditional.conditions) {
420
356
                operands.push_back(
421
356
                    lower_expression(*condition.expr, source_manager));
422
356
            }
423
356
            operands.push_back(
424
356
                lower_expression(conditional.left(), source_manager));
425
356
            operands.push_back(
426
356
                lower_expression(conditional.right(), source_manager));
427
356
            return {labneura::eda::ExpressionKind::Conditional, "?:", source,
428
356
                    std::move(operands), expression.type->getBitWidth()};
429
2.22k
        }
430
183
        case ExpressionKind::Concatenation: {
431
183
            const auto& concat =
432
183
                expression.as<slang::ast::ConcatenationExpression>();
433
183
            std::vector<labneura::eda::Expression> operands;
434
486
            for (const auto* operand : concat.operands()) {
435
486
                operands.push_back(lower_expression(*operand, source_manager));
436
486
            }
437
183
            return {labneura::eda::ExpressionKind::Concatenation, "", source,
438
183
                    std::move(operands), expression.type->getBitWidth()};
439
2.22k
        }
440
980
        case ExpressionKind::Conversion: {
441
980
            auto operand = lower_expression(
442
980
                expression.as<slang::ast::ConversionExpression>().operand(),
443
980
                source_manager);
444
980
            const auto width = expression.type->getBitWidth();
445
980
            if (width == operand.get_width()) return operand;
446
107
            if (operand.get_kind() ==
447
107
                    labneura::eda::ExpressionKind::Literal &&
448
107
                width == 1) {
449
23
                return {operand.get_kind(), operand.get_value(), source, {},
450
23
                        width};
451
23
            }
452
84
            return {labneura::eda::ExpressionKind::Opaque,
453
84
                    "implicit_conversion", source, {std::move(operand)}, width};
454
107
        }
455
461
        default:
456
461
            return {labneura::eda::ExpressionKind::Opaque, "", source, {},
457
461
                    expression.type->getBitWidth()};
458
20.2k
    }
459
20.2k
}
460
461
template <typename Callback>
462
void visit_generate_instances(const slang::ast::Scope& scope,
463
465
                              Callback&& callback) {
464
465
    const auto visit_scope = [&](const auto& self,
465
465
                                 const slang::ast::Scope& current,
466
2.28k
                                 bool inside_generate) -> void {
467
37.8k
        for (const auto& member : current.members()) {
468
37.8k
            if (member.kind == slang::ast::SymbolKind::Instance) {
469
376
                if (inside_generate) {
470
17
                    callback(member.as<slang::ast::InstanceSymbol>());
471
17
                }
472
37.4k
            } else if (member.kind == slang::ast::SymbolKind::GenerateBlock) {
473
1.87k
                const auto& block =
474
1.87k
                    member.as<slang::ast::GenerateBlockSymbol>();
475
1.87k
                if (!block.isUninstantiated) self(self, block, true);
476
35.6k
            } else if (member.kind ==
477
35.6k
                       slang::ast::SymbolKind::GenerateBlockArray) {
478
82
                const auto& array =
479
82
                    member.as<slang::ast::GenerateBlockArraySymbol>();
480
992
                for (const auto* entry : array.entries) {
481
992
                    if (!entry->isUninstantiated) self(self, *entry, true);
482
992
                }
483
82
            }
484
37.8k
        }
485
2.28k
    };
verilog_parser.cpp:_ZZN8labneura3eda12_GLOBAL__N_124visit_generate_instancesIZNS1_16summarize_moduleERKN5slang3ast14InstanceSymbolERKNS3_13SourceManagerEbbNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEE3$_0EEvRKNS4_5ScopeEOT_ENKUlRKSL_SK_bE_clISP_EEvSO_SK_b
Line
Count
Source
466
1.29k
                                 bool inside_generate) -> void {
467
20.2k
        for (const auto& member : current.members()) {
468
20.2k
            if (member.kind == slang::ast::SymbolKind::Instance) {
469
244
                if (inside_generate) {
470
9
                    callback(member.as<slang::ast::InstanceSymbol>());
471
9
                }
472
19.9k
            } else if (member.kind == slang::ast::SymbolKind::GenerateBlock) {
473
939
                const auto& block =
474
939
                    member.as<slang::ast::GenerateBlockSymbol>();
475
939
                if (!block.isUninstantiated) self(self, block, true);
476
19.0k
            } else if (member.kind ==
477
19.0k
                       slang::ast::SymbolKind::GenerateBlockArray) {
478
42
                const auto& array =
479
42
                    member.as<slang::ast::GenerateBlockArraySymbol>();
480
500
                for (const auto* entry : array.entries) {
481
500
                    if (!entry->isUninstantiated) self(self, *entry, true);
482
500
                }
483
42
            }
484
20.2k
        }
485
1.29k
    };
verilog_parser.cpp:_ZZN8labneura3eda12_GLOBAL__N_124visit_generate_instancesIZZNS0_23parse_verilog_directoryERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEENK3$_0clISB_EEvRKT_RKN5slang3ast14InstanceSymbolEEUlSF_E_EEvRKNSH_5ScopeEOSD_ENKUlSF_SO_bE_clISQ_EEvSF_SO_b
Line
Count
Source
466
992
                                 bool inside_generate) -> void {
467
17.6k
        for (const auto& member : current.members()) {
468
17.6k
            if (member.kind == slang::ast::SymbolKind::Instance) {
469
132
                if (inside_generate) {
470
8
                    callback(member.as<slang::ast::InstanceSymbol>());
471
8
                }
472
17.5k
            } else if (member.kind == slang::ast::SymbolKind::GenerateBlock) {
473
935
                const auto& block =
474
935
                    member.as<slang::ast::GenerateBlockSymbol>();
475
935
                if (!block.isUninstantiated) self(self, block, true);
476
16.5k
            } else if (member.kind ==
477
16.5k
                       slang::ast::SymbolKind::GenerateBlockArray) {
478
40
                const auto& array =
479
40
                    member.as<slang::ast::GenerateBlockArraySymbol>();
480
492
                for (const auto* entry : array.entries) {
481
492
                    if (!entry->isUninstantiated) self(self, *entry, true);
482
492
                }
483
40
            }
484
17.6k
        }
485
992
    };
486
465
    visit_scope(visit_scope, scope, false);
487
465
}
verilog_parser.cpp:_ZN8labneura3eda12_GLOBAL__N_124visit_generate_instancesIZNS1_16summarize_moduleERKN5slang3ast14InstanceSymbolERKNS3_13SourceManagerEbbNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEE3$_0EEvRKNS4_5ScopeEOT_
Line
Count
Source
463
379
                              Callback&& callback) {
464
379
    const auto visit_scope = [&](const auto& self,
465
379
                                 const slang::ast::Scope& current,
466
379
                                 bool inside_generate) -> void {
467
379
        for (const auto& member : current.members()) {
468
379
            if (member.kind == slang::ast::SymbolKind::Instance) {
469
379
                if (inside_generate) {
470
379
                    callback(member.as<slang::ast::InstanceSymbol>());
471
379
                }
472
379
            } else if (member.kind == slang::ast::SymbolKind::GenerateBlock) {
473
379
                const auto& block =
474
379
                    member.as<slang::ast::GenerateBlockSymbol>();
475
379
                if (!block.isUninstantiated) self(self, block, true);
476
379
            } else if (member.kind ==
477
379
                       slang::ast::SymbolKind::GenerateBlockArray) {
478
379
                const auto& array =
479
379
                    member.as<slang::ast::GenerateBlockArraySymbol>();
480
379
                for (const auto* entry : array.entries) {
481
379
                    if (!entry->isUninstantiated) self(self, *entry, true);
482
379
                }
483
379
            }
484
379
        }
485
379
    };
486
379
    visit_scope(visit_scope, scope, false);
487
379
}
verilog_parser.cpp:_ZN8labneura3eda12_GLOBAL__N_124visit_generate_instancesIZZNS0_23parse_verilog_directoryERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEENK3$_0clISB_EEvRKT_RKN5slang3ast14InstanceSymbolEEUlSF_E_EEvRKNSH_5ScopeEOSD_
Line
Count
Source
463
86
                              Callback&& callback) {
464
86
    const auto visit_scope = [&](const auto& self,
465
86
                                 const slang::ast::Scope& current,
466
86
                                 bool inside_generate) -> void {
467
86
        for (const auto& member : current.members()) {
468
86
            if (member.kind == slang::ast::SymbolKind::Instance) {
469
86
                if (inside_generate) {
470
86
                    callback(member.as<slang::ast::InstanceSymbol>());
471
86
                }
472
86
            } else if (member.kind == slang::ast::SymbolKind::GenerateBlock) {
473
86
                const auto& block =
474
86
                    member.as<slang::ast::GenerateBlockSymbol>();
475
86
                if (!block.isUninstantiated) self(self, block, true);
476
86
            } else if (member.kind ==
477
86
                       slang::ast::SymbolKind::GenerateBlockArray) {
478
86
                const auto& array =
479
86
                    member.as<slang::ast::GenerateBlockArraySymbol>();
480
86
                for (const auto* entry : array.entries) {
481
86
                    if (!entry->isUninstantiated) self(self, *entry, true);
482
86
                }
483
86
            }
484
86
        }
485
86
    };
486
86
    visit_scope(visit_scope, scope, false);
487
86
}
488
489
template <typename Callback>
490
void visit_generate_assignments(const slang::ast::Scope& scope,
491
379
                                Callback&& callback) {
492
379
    const auto visit_scope = [&](const auto& self,
493
379
                                 const slang::ast::Scope& current,
494
1.29k
                                 bool inside_generate) -> void {
495
20.2k
        for (const auto& member : current.members()) {
496
20.2k
            if (inside_generate &&
497
20.2k
                member.kind == slang::ast::SymbolKind::ContinuousAssign) {
498
1.68k
                callback(member.as<slang::ast::ContinuousAssignSymbol>());
499
18.5k
            } else if (member.kind == slang::ast::SymbolKind::GenerateBlock) {
500
939
                const auto& block =
501
939
                    member.as<slang::ast::GenerateBlockSymbol>();
502
939
                if (!block.isUninstantiated) self(self, block, true);
503
17.5k
            } else if (member.kind ==
504
17.5k
                       slang::ast::SymbolKind::GenerateBlockArray) {
505
42
                const auto& array =
506
42
                    member.as<slang::ast::GenerateBlockArraySymbol>();
507
500
                for (const auto* entry : array.entries) {
508
500
                    if (!entry->isUninstantiated) self(self, *entry, true);
509
500
                }
510
42
            }
511
20.2k
        }
512
1.29k
    };
513
379
    visit_scope(visit_scope, scope, false);
514
379
}
515
516
Module summarize_module(const slang::ast::InstanceSymbol& instance,
517
                       const slang::SourceManager& source_manager,
518
                       bool project_summary = false,
519
                       bool preserve_hierarchy = false,
520
380
                       std::string hierarchy_instance_name = {}) {
521
380
    bool behavioral = false;
522
380
    std::vector<Port> ports;
523
380
    std::vector<Net> nets;
524
380
    std::vector<Instance> instances;
525
380
    std::vector<Module> child_modules;
526
380
    std::vector<ContinuousAssignment> assignments;
527
380
    std::unordered_set<std::string> port_names;
528
380
    const std::string scope_prefix =
529
380
        std::string(instance.getHierarchicalPath()) + ".";
530
531
4.03k
    for (const auto* port_symbol : instance.body.getPortList()) {
532
4.03k
        if (port_symbol->kind != slang::ast::SymbolKind::Port) continue;
533
4.03k
        const auto& port = port_symbol->as<slang::ast::PortSymbol>();
534
4.03k
        const std::string port_name(port.name);
535
4.03k
        port_names.insert(port_name);
536
4.03k
        PortDirection direction = PortDirection::InOut;
537
4.03k
        if (port.direction == slang::ast::ArgumentDirection::In) {
538
2.16k
            direction = PortDirection::Input;
539
2.16k
        } else if (port.direction == slang::ast::ArgumentDirection::Out) {
540
1.86k
            direction = PortDirection::Output;
541
1.86k
        }
542
4.03k
        const auto shape = declared_shape(port.getType());
543
4.03k
        ports.emplace_back(port_name, direction, shape.width,
544
4.03k
                           shape.packed_left, shape.packed_right,
545
4.03k
                           shape.unpacked_left, shape.unpacked_right,
546
4.03k
                           shape.packed_width);
547
4.03k
        const auto net_type =
548
4.03k
            direction == PortDirection::Input
549
4.03k
                ? NetType::Input
550
4.03k
                : direction == PortDirection::Output ? NetType::Output
551
1.86k
                                                     : NetType::InOut;
552
4.03k
        nets.emplace_back(port_name, net_type, shape.width,
553
4.03k
                          shape.packed_left, shape.packed_right,
554
4.03k
                          shape.unpacked_left, shape.unpacked_right,
555
4.03k
                          shape.packed_width);
556
4.03k
    }
557
558
16.7k
    for (const auto& member : instance.body.members()) {
559
16.7k
        if ((member.kind == slang::ast::SymbolKind::Net ||
560
16.7k
             member.kind == slang::ast::SymbolKind::Variable) &&
561
16.7k
            port_names.count(std::string(member.name)) == 0) {
562
3.94k
             const auto* declared_type = member.getDeclaredType();
563
3.94k
             const auto shape = declared_type
564
3.94k
                                    ? declared_shape(declared_type->getType())
565
3.94k
                                    : DeclaredShape{};
566
3.94k
             nets.emplace_back(std::string(member.name), NetType::Internal,
567
3.94k
                               shape.width, shape.packed_left,
568
3.94k
                               shape.packed_right, shape.unpacked_left,
569
3.94k
                               shape.unpacked_right, shape.packed_width);
570
12.8k
        } else if (member.kind == slang::ast::SymbolKind::Instance) {
571
235
            const auto& child = member.as<slang::ast::InstanceSymbol>();
572
235
            const std::string cell_type(child.getDefinition().name);
573
235
            instances.emplace_back(
574
235
                std::string(child.name), cell_type,
575
235
                module_port_connections(child, source_manager, scope_prefix),
576
235
                std::nullopt,
577
235
                std::map<std::string, std::string>{});
578
235
            if (preserve_hierarchy && child.isModule()) {
579
111
                child_modules.push_back(summarize_module(
580
111
                    child, source_manager, false, true,
581
111
                    std::string(child.name)));
582
111
            }
583
12.5k
        } else if (member.kind == slang::ast::SymbolKind::PrimitiveInstance) {
584
70
            const auto& child =
585
70
                member.as<slang::ast::PrimitiveInstanceSymbol>();
586
70
            const std::string cell_type(child.primitiveType.name);
587
70
            std::vector<UserDefinedPrimitiveRow> primitive_table;
588
70
            if (child.primitiveType.primitiveKind ==
589
70
                slang::ast::PrimitiveSymbol::UserDefined) {
590
1
                primitive_table.reserve(child.primitiveType.table.size());
591
4
                for (const auto& row : child.primitiveType.table) {
592
4
                    primitive_table.push_back(
593
4
                        {std::string(row.inputs), row.output});
594
4
                }
595
1
            }
596
70
            instances.emplace_back(
597
70
                std::string(child.name), cell_type,
598
70
                parsed_primitive_connections(child, source_manager,
599
70
                                             scope_prefix),
600
70
                std::nullopt, std::map<std::string, std::string>{},
601
70
                child.primitiveType.primitiveKind ==
602
70
                    slang::ast::PrimitiveSymbol::UserDefined,
603
70
                std::move(primitive_table),
604
70
                child.primitiveType.isSequential ||
605
70
                    child.primitiveType.isEdgeSensitive);
606
12.5k
        } else if (member.kind == slang::ast::SymbolKind::ContinuousAssign) {
607
1.90k
            const auto& assignment =
608
1.90k
                member.as<slang::ast::ContinuousAssignSymbol>().getAssignment()
609
1.90k
                    .as<slang::ast::AssignmentExpression>();
610
1.90k
            assignments.emplace_back(
611
1.90k
                lower_expression(assignment.left(), source_manager),
612
1.90k
                lower_expression(assignment.right(), source_manager));
613
10.6k
        } else if (member.kind == slang::ast::SymbolKind::ProceduralBlock) {
614
765
            const auto& block =
615
765
                member.as<slang::ast::ProceduralBlockSymbol>();
616
765
            if (block.procedureKind == slang::ast::ProceduralBlockKind::Initial ||
617
765
                block.procedureKind == slang::ast::ProceduralBlockKind::Final) {
618
24
                if (project_summary) continue;
619
1
                throw std::runtime_error(
620
1
                    "procedural block '" +
621
1
                    std::string(slang::ast::SemanticFacts::getProcedureKindStr(
622
1
                        block.procedureKind)) +
623
1
                    "' is simulation-only and has no netlist form");
624
24
            }
625
741
            behavioral = true;
626
741
        }
627
16.7k
    }
628
629
379
    visit_generate_instances(instance.body, [&](const auto& child) {
630
9
        const std::string cell_type(child.getDefinition().name);
631
9
        instances.emplace_back(
632
9
            std::string(child.name), cell_type,
633
9
            module_port_connections(child, source_manager, scope_prefix));
634
9
        if (preserve_hierarchy && child.isModule()) {
635
1
            child_modules.push_back(summarize_module(
636
1
                child, source_manager, false, true, std::string(child.name)));
637
1
        }
638
9
    });
639
640
1.68k
    visit_generate_assignments(instance.body, [&](const auto& symbol) {
641
1.68k
        const auto& assignment =
642
1.68k
            symbol.getAssignment()
643
1.68k
                .template as<slang::ast::AssignmentExpression>();
644
1.68k
        assignments.emplace_back(
645
1.68k
            lower_expression(assignment.left(), source_manager),
646
1.68k
            lower_expression(assignment.right(), source_manager));
647
1.68k
    });
648
649
379
    return Module(std::string(instance.getDefinition().name), std::move(ports),
650
379
                  std::move(nets), std::move(instances),
651
379
                  std::move(assignments), behavioral,
652
379
                  std::move(hierarchy_instance_name),
653
379
                  std::move(child_modules));
654
380
}
655
656
}  // namespace
657
658
std::string detail::verilog_expression_source(
659
    const slang::ast::Expression& expression,
660
    const slang::SourceManager& source_manager,
661
1.08k
    const std::string& scope_prefix) {
662
1.08k
    return expression_source(expression, source_manager, scope_prefix);
663
1.08k
}
664
665
183
Module parse_verilog(const std::string& path) {
666
183
    const std::filesystem::path source_path(path);
667
183
    if (!std::filesystem::is_regular_file(source_path)) {
668
0
        throw std::runtime_error("could not open Verilog file: " + path);
669
0
    }
670
671
183
    const auto absolute_path =
672
183
        std::filesystem::absolute(source_path).lexically_normal().string();
673
183
    const auto source_directory =
674
183
        source_path.has_parent_path() ? source_path.parent_path()
675
183
                                      : std::filesystem::path(".");
676
183
    const auto include_directory =
677
183
        std::filesystem::absolute(source_directory)
678
183
            .lexically_normal()
679
183
            .string();
680
183
    std::vector<std::string> arguments = {
681
183
        "labneura-eda",
682
183
        is_systemverilog(source_path) ? "--std=1800-2017" : "--std=1364-2005",
683
183
        "--include-directory=" + include_directory, absolute_path};
684
685
183
    auto parsed_context = parse_sources(arguments, "Verilog file");
686
183
    auto& driver = parsed_context->driver;
687
183
    const auto& root_symbol = parsed_context->compilation->getRoot();
688
183
    const slang::ast::InstanceSymbol* top_module = nullptr;
689
183
    for (const auto* candidate : root_symbol.topInstances) {
690
182
        if (top_module) {
691
0
            throw std::runtime_error(
692
0
                "parse_verilog requires exactly one top-level module in the file");
693
0
        }
694
182
        top_module = candidate;
695
182
    }
696
183
    if (!top_module) {
697
0
        throw std::runtime_error(
698
0
            "parse_verilog found no top-level Verilog module in the file");
699
0
    }
700
183
    auto module = summarize_module(*top_module, driver.sourceManager, false,
701
183
                                   true);
702
183
    module.parsed_context_ = parsed_context;
703
183
    const auto retain_behavioral_context =
704
293
        [&](const auto& self, Module& current) -> void {
705
293
        current.parsed_context_ = parsed_context;
706
293
        for (auto& child : current.child_modules_) self(self, child);
707
293
    };
708
183
    retain_behavioral_context(retain_behavioral_context, module);
709
710
183
    return module;
711
183
}
712
713
10
Module read_verilog(const std::string& path) {
714
10
    auto module = parse_verilog(path);
715
14
    const auto normalize = [&](const auto& self, Module& current) -> void {
716
14
        std::unordered_map<std::string, std::string> cell_types;
717
14
        std::vector<Module> children;
718
14
        children.reserve(current.child_modules_.size());
719
106
        for (auto& child : current.child_modules_) {
720
106
            if (child.get_name().rfind("__labneura_cell__", 0) == 0) {
721
102
                static constexpr char digits[] = "0123456789abcdef";
722
102
                constexpr std::string_view prefix = "__labneura_cell__";
723
102
                const std::string_view encoded(child.get_name().data() +
724
102
                                                   prefix.size(),
725
102
                                               child.get_name().size() -
726
102
                                                   prefix.size());
727
102
                std::string type;
728
102
                if (encoded.size() % 2 != 0) {
729
0
                    throw std::runtime_error(
730
0
                        "invalid internal black-box name in Verilog netlist");
731
0
                }
732
409
                for (std::size_t i = 0; i < encoded.size(); i += 2) {
733
307
                    const auto high = std::string_view(digits).find(encoded[i]);
734
307
                    const auto low = std::string_view(digits).find(encoded[i + 1]);
735
307
                    if (high == std::string_view::npos ||
736
307
                        low == std::string_view::npos) {
737
0
                        throw std::runtime_error(
738
0
                            "invalid internal black-box name in Verilog netlist");
739
0
                    }
740
307
                    type.push_back(static_cast<char>((high << 4) | low));
741
307
                }
742
102
                cell_types[child.get_hierarchy_instance_name()] = std::move(type);
743
102
                continue;
744
102
            }
745
4
            self(self, child);
746
4
            children.push_back(child);
747
4
        }
748
749
14
        std::vector<Instance> instances;
750
14
        instances.reserve(current.instances_.size());
751
110
        for (const auto& instance : current.instances_) {
752
110
            const auto cell = cell_types.find(instance.get_name());
753
110
            instances.emplace_back(
754
110
                instance.get_name(),
755
110
                cell == cell_types.end() ? instance.get_cell_type() : cell->second,
756
110
                instance.get_connections(), instance.get_cell(),
757
110
                instance.get_parameters(), instance.is_user_defined_primitive(),
758
110
                instance.get_primitive_table(), instance.is_sequential_primitive());
759
110
        }
760
14
        Module normalized(
761
14
            current.get_name(), current.get_ports(), current.get_nets(),
762
14
            std::move(instances), current.get_assignments(),
763
14
            current.is_behavioral(), current.get_hierarchy_instance_name(),
764
14
            std::move(children));
765
14
        normalized.parsed_context_ = current.parsed_context_;
766
14
        current = std::move(normalized);
767
14
    };
768
10
    normalize(normalize, module);
769
10
    return module;
770
10
}
771
772
13
Project parse_verilog_directory(const std::string& directory) {
773
13
    const std::filesystem::path root(directory);
774
13
    if (!std::filesystem::is_directory(root)) {
775
0
        throw std::runtime_error("Verilog project path is not a directory: " +
776
0
                                 directory);
777
0
    }
778
779
13
    std::vector<std::filesystem::path> verilog_files;
780
13
    std::unordered_set<std::string> include_directories;
781
13
    include_directories.insert(
782
13
        std::filesystem::absolute(root).lexically_normal().string());
783
161
    for (const auto& entry : std::filesystem::recursive_directory_iterator(root)) {
784
161
        if (entry.is_directory()) {
785
3
            include_directories.insert(
786
3
                std::filesystem::absolute(entry.path()).lexically_normal().string());
787
3
        }
788
161
        if (entry.is_regular_file() && (entry.path().extension() == ".v" || is_systemverilog(entry.path()))) {
789
122
            verilog_files.push_back(entry.path());
790
122
        }
791
161
    }
792
13
    std::sort(verilog_files.begin(), verilog_files.end());
793
13
    if (verilog_files.empty()) {
794
0
        throw std::runtime_error("no .v or .sv files found in project: " +
795
0
                                 directory);
796
0
    }
797
798
13
    Project project;
799
13
    const bool any_systemverilog =
800
13
        std::any_of(verilog_files.begin(), verilog_files.end(), is_systemverilog);
801
13
    std::vector<std::string> arguments = {
802
13
        "labneura-eda", any_systemverilog ? "--std=1800-2017" : "--std=1364-2005"};
803
122
    for (const auto& path : verilog_files) {
804
122
        project.source_files_.push_back(
805
122
            std::filesystem::absolute(path).lexically_normal().string());
806
122
    }
807
13
    std::vector<std::string> sorted_include_directories(include_directories.begin(),
808
13
                                                        include_directories.end());
809
13
    std::sort(sorted_include_directories.begin(), sorted_include_directories.end());
810
16
    for (const auto& include_directory : sorted_include_directories) {
811
16
        arguments.push_back("--include-directory=" + include_directory);
812
16
    }
813
122
    for (const auto& source_file : project.source_files_) {
814
122
        arguments.push_back(source_file);
815
122
    }
816
817
13
    project.parsed_context_ = parse_sources(arguments, "Verilog project");
818
13
    auto& driver = project.parsed_context_->driver;
819
13
    const auto& root_symbol = project.parsed_context_->compilation->getRoot();
820
821
13
    slang::JsonWriter writer;
822
13
    writer.setPrettyPrint(true);
823
13
    slang::ast::ASTSerializer serializer(*project.parsed_context_->compilation,
824
13
                                         writer);
825
13
    serializer.setIncludeAddresses(false);
826
13
    serializer.setIncludeSourceInfo(true);
827
13
    writer.startObject();
828
13
    writer.writeProperty("definitions");
829
13
    writer.startArray();
830
13
    for (const auto* definition :
831
107
         project.parsed_context_->compilation->getDefinitions()) {
832
107
        serializer.serialize(*definition);
833
107
    }
834
13
    writer.endArray();
835
13
    writer.writeProperty("elaborated_root");
836
13
    serializer.serialize(root_symbol);
837
13
    writer.endObject();
838
13
    project.ast_json_ = std::string(writer.view());
839
840
13
    std::unordered_set<std::string> module_names;
841
13
    std::vector<Module> modules;
842
13
    const auto collect_module = [&](const auto& self,
843
150
                                    const slang::ast::InstanceSymbol& instance) -> void {
844
150
        if (!instance.isModule()) return;
845
846
150
        const std::string module_name(instance.getDefinition().name);
847
150
        if (module_names.insert(module_name).second) {
848
86
            auto module = summarize_module(instance, driver.sourceManager, true);
849
86
            module.parsed_context_ = project.parsed_context_;
850
86
            modules.push_back(std::move(module));
851
852
14.2k
            for (const auto& member : instance.body.members()) {
853
14.2k
                if (member.kind == slang::ast::SymbolKind::Instance) {
854
124
                    self(self, member.as<slang::ast::InstanceSymbol>());
855
124
                }
856
14.2k
            }
857
86
            visit_generate_instances(instance.body, [&](const auto& child) {
858
8
                self(self, child);
859
8
            });
860
86
        }
861
150
    };
862
18
    for (const auto* top : root_symbol.topInstances) {
863
18
        collect_module(collect_module, *top);
864
18
    }
865
13
    if (modules.empty()) {
866
0
        throw std::runtime_error("no Verilog modules found in project: " + directory);
867
0
    }
868
13
    project.modules_ = std::move(modules);
869
870
13
    return project;
871
13
}
872
873
}  // namespace labneura::eda