Coverage Report

Created: 2026-11-03 04:34

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