Coverage Report

Created: 2026-11-07 16:24

/home/runner/work/LabNeura/LabNeura/src/labneura/eda/netlist/netlist_verilog.cpp
Line
Count
Source (jump to first uncovered line)
1
#include "labneura/eda/netlist.h"
2
3
#include <algorithm>
4
#include <cctype>
5
#include <fstream>
6
#include <map>
7
#include <ostream>
8
#include <set>
9
#include <sstream>
10
#include <stdexcept>
11
#include <string>
12
#include <unordered_map>
13
#include <unordered_set>
14
#include <utility>
15
#include <vector>
16
17
namespace labneura::eda {
18
namespace {
19
20
751
bool simple_identifier(const std::string& value) {
21
751
    if (value.empty() ||
22
751
        !(std::isalpha(static_cast<unsigned char>(value.front())) ||
23
751
          value.front() == '_' || value.front() == '$')) {
24
0
        return false;
25
0
    }
26
4.09k
    return std::all_of(value.begin() + 1, value.end(), [](unsigned char ch) {
27
4.09k
        return std::isalnum(ch) || ch == '_' || ch == '$';
28
4.09k
    });
29
751
}
30
31
751
std::string identifier(const std::string& value) {
32
751
    if (simple_identifier(value)) return value;
33
1
    if (value.find_first_of(" \t\r\n") != std::string::npos) {
34
0
        throw std::runtime_error("cannot emit Verilog identifier containing whitespace: " +
35
0
                                 value);
36
0
    }
37
1
    return "\\" + value + " ";
38
1
}
39
40
222
std::string signal_reference(const std::string& value) {
41
222
    if (value.empty() || value.front() == '\\') return value;
42
222
    const auto dot = value.rfind('.');
43
222
    const auto select = value.find('[', dot == std::string::npos ? 0 : dot + 1);
44
222
    const auto base = value.substr(0, select);
45
222
    const bool scoped_identifier = !base.empty() &&
46
252
        std::all_of(base.begin(), base.end(), [](unsigned char ch) {
47
252
            return std::isalnum(ch) || ch == '_' || ch == '$' || ch == '.' ||
48
252
                   ch == '[' || ch == ']';
49
252
        });
50
222
    if (!scoped_identifier) return value;
51
222
    return identifier(base) + (select == std::string::npos
52
222
                                   ? std::string{}
53
222
                                   : value.substr(select));
54
222
}
55
56
std::string range(std::size_t width,
57
                  const std::optional<std::int64_t>& left = std::nullopt,
58
30
                  const std::optional<std::int64_t>& right = std::nullopt) {
59
30
    if (left && right) {
60
14
        return " [" + std::to_string(*left) + ":" +
61
14
               std::to_string(*right) + "]";
62
14
    }
63
16
    return width > 1 ? " [" + std::to_string(width - 1) + ":0]" : "";
64
30
}
65
66
struct NetGroup {
67
    std::string base;
68
    std::vector<std::set<std::int64_t>> indices;
69
    bool has_scalar = false;
70
    std::size_t width = 1;
71
    std::size_t packed_width = 1;
72
    std::optional<std::int64_t> packed_left;
73
    std::optional<std::int64_t> packed_right;
74
    std::optional<std::int64_t> unpacked_left;
75
    std::optional<std::int64_t> unpacked_right;
76
};
77
78
0
bool parse_index(const std::string& value, std::int64_t& index) {
79
0
    try {
80
0
        std::size_t consumed = 0;
81
0
        index = std::stoll(value, &consumed);
82
0
        return consumed == value.size();
83
0
    } catch (const std::exception&) {
84
0
        return false;
85
0
    }
86
0
}
87
88
std::pair<std::string, std::vector<std::int64_t>> split_net_indices(
89
1
    const std::string& name) {
90
1
    std::string base = name;
91
1
    std::vector<std::int64_t> indices;
92
1
    while (!base.empty() && base.back() == ']') {
93
0
        const auto open = base.rfind('[');
94
0
        if (open == std::string::npos) break;
95
0
        std::int64_t index = 0;
96
0
        if (!parse_index(base.substr(open + 1, base.size() - open - 2), index)) {
97
0
            break;
98
0
        }
99
0
        indices.push_back(index);
100
0
        base.resize(open);
101
0
    }
102
1
    if (indices.empty()) return {name, {}};
103
0
    std::reverse(indices.begin(), indices.end());
104
0
    return {std::move(base), std::move(indices)};
105
1
}
106
107
13
std::vector<std::string> internal_declarations(const Module& module) {
108
13
    std::unordered_set<std::string> ports;
109
29
    for (const auto& port : module.get_ports()) ports.insert(port.get_name());
110
111
13
    std::map<std::string, NetGroup> groups;
112
36
    for (const auto& net : module.get_nets()) {
113
36
        if (net.get_kind() != NetType::Internal) continue;
114
1
        auto [base, indices] = split_net_indices(net.get_name());
115
1
        auto& group = groups[base];
116
1
        group.base = base;
117
1
        if (!indices.empty()) {
118
0
            if (group.indices.empty()) {
119
0
                group.indices.resize(indices.size());
120
0
            } else if (group.indices.size() != indices.size()) {
121
0
                throw std::runtime_error(
122
0
                    "inconsistent dimensionality for net '" + base + "'");
123
0
            }
124
0
            for (std::size_t dimension = 0; dimension < indices.size(); ++dimension) {
125
0
                group.indices[dimension].insert(indices[dimension]);
126
0
            }
127
1
        } else {
128
1
            group.has_scalar = true;
129
1
            group.width = net.get_width();
130
1
            group.packed_width = net.get_packed_width();
131
1
            group.packed_left = net.get_left_index();
132
1
            group.packed_right = net.get_right_index();
133
1
            group.unpacked_left = net.get_unpacked_left_index();
134
1
            group.unpacked_right = net.get_unpacked_right_index();
135
1
        }
136
1
    }
137
138
13
    std::vector<std::string> declarations;
139
13
    declarations.reserve(groups.size());
140
13
    for (const auto& [key, group] : groups) {
141
1
        if (ports.count(group.base)) continue;
142
1
        std::string declaration = "wire";
143
1
        if (group.unpacked_left && group.unpacked_right) {
144
0
            declaration += range(group.packed_width, group.packed_left,
145
0
                                 group.packed_right);
146
0
            declaration += " " + identifier(group.base);
147
0
            declaration += " [" + std::to_string(*group.unpacked_left) +
148
0
                           ":" + std::to_string(*group.unpacked_right) + "]";
149
1
        } else if (group.packed_left && group.packed_right) {
150
1
            declaration += range(group.packed_width, group.packed_left,
151
1
                                 group.packed_right);
152
1
            declaration += " " + identifier(group.base);
153
1
        } else if (!group.indices.empty()) {
154
0
            const auto& packed = group.indices.back();
155
0
            declaration += " [" + std::to_string(*packed.rbegin()) + ":" +
156
0
                           std::to_string(*packed.begin()) + "]";
157
0
            declaration += " " + identifier(group.base);
158
0
            for (std::size_t dimension = 0;
159
0
                 dimension + 1 < group.indices.size(); ++dimension) {
160
0
                const auto& values = group.indices[dimension];
161
0
                declaration += " [" + std::to_string(*values.rbegin()) + ":" +
162
0
                               std::to_string(*values.begin()) + "]";
163
0
            }
164
0
        } else {
165
0
            declaration += range(group.packed_width, group.packed_left,
166
0
                                 group.packed_right);
167
0
            declaration += " " + identifier(group.base);
168
0
            if (group.unpacked_left && group.unpacked_right) {
169
0
                declaration += " [" + std::to_string(*group.unpacked_left) +
170
0
                               ":" + std::to_string(*group.unpacked_right) + "]";
171
0
            }
172
0
        }
173
1
        declaration += ";";
174
1
        declarations.push_back(std::move(declaration));
175
1
    }
176
13
    return declarations;
177
13
}
178
179
212
bool is_gate_primitive(const std::string& type) {
180
212
    static const std::unordered_set<std::string> types = {
181
212
        "and", "nand", "or", "nor", "xor", "xnor", "buf", "not",
182
212
        "bufif0", "bufif1", "notif0", "notif1", "pullup", "pulldown",
183
212
        "nmos", "pmos", "rnmos", "rpmos", "cmos", "rcmos", "tran",
184
212
        "rtran", "tranif0", "tranif1", "rtranif0", "rtranif1"};
185
212
    return types.count(type) != 0;
186
212
}
187
188
15
bool output_pin_name(const std::string& pin) {
189
15
    static const std::unordered_set<std::string> outputs = {
190
15
        "Y", "Q", "X", "Z", "ZN", "QN", "Q_N", "HI", "LO",
191
15
        "SUM", "COUT", "O"};
192
15
    return outputs.count(pin) != 0;
193
15
}
194
195
102
std::string cell_module_alias(const std::string& type) {
196
102
    static constexpr char hex[] = "0123456789abcdef";
197
102
    std::string alias = "__labneura_cell__";
198
307
    for (const unsigned char ch : type) {
199
307
        alias.push_back(hex[ch >> 4]);
200
307
        alias.push_back(hex[ch & 0x0f]);
201
307
    }
202
102
    return alias;
203
102
}
204
205
void emit_instance(std::ostream& out, const Instance& instance,
206
108
                   const std::string& cell_type) {
207
108
    if (instance.is_user_defined_primitive()) {
208
0
        throw std::runtime_error(
209
0
            "Verilog writer cannot reconstruct user-defined primitive declarations");
210
0
    }
211
108
    out << "  " << identifier(cell_type);
212
108
    if (!instance.get_parameters().empty()) {
213
0
        out << " #(";
214
0
        bool first = true;
215
0
        for (const auto& [name, value] : instance.get_parameters()) {
216
0
            out << (first ? "" : ", ") << "." << identifier(name) << "("
217
0
                << value << ")";
218
0
            first = false;
219
0
        }
220
0
        out << ")";
221
0
    }
222
108
    out << " " << identifier(instance.get_name()) << " (";
223
224
108
    if (is_gate_primitive(cell_type)) {
225
2
        std::vector<const PinConnection*> outputs;
226
2
        std::vector<const PinConnection*> inputs;
227
5
        for (const auto& connection : instance.get_connections()) {
228
5
            (output_pin_name(connection.get_pin()) ? outputs : inputs)
229
5
                .push_back(&connection);
230
5
        }
231
2
        std::sort(inputs.begin(), inputs.end(),
232
2
                  [](const auto* lhs, const auto* rhs) {
233
2
                      return lhs->get_pin() < rhs->get_pin();
234
2
                  });
235
2
        bool first = true;
236
2
        for (const auto* connection : outputs) {
237
2
            out << (first ? "" : ", ")
238
2
                << signal_reference(connection->get_net());
239
2
            first = false;
240
2
        }
241
3
        for (const auto* connection : inputs) {
242
3
            out << (first ? "" : ", ")
243
3
                << signal_reference(connection->get_net());
244
3
            first = false;
245
3
        }
246
106
    } else {
247
106
        bool first = true;
248
217
        for (const auto& connection : instance.get_connections()) {
249
217
            out << (first ? "" : ", ") << "." << identifier(connection.get_pin())
250
217
                << "(" << signal_reference(connection.get_net()) << ")";
251
217
            first = false;
252
217
        }
253
106
    }
254
108
    out << ");\n";
255
108
}
256
257
struct EmissionNode {
258
    const Module* module;
259
    std::string emitted_name;
260
    std::unordered_map<std::string, std::string> child_types;
261
};
262
263
27
void validate_structural(const Module& module) {
264
27
    if (module.is_behavioral()) {
265
1
        throw std::runtime_error(
266
1
            "Verilog writer requires structural RTL; generic_map behavioral "
267
1
            "modules before writing");
268
1
    }
269
216
    for (const auto& instance : module.get_instances()) {
270
216
        if (instance.is_user_defined_primitive()) {
271
0
            throw std::runtime_error(
272
0
                "Verilog writer cannot reconstruct user-defined primitive declarations");
273
0
        }
274
216
    }
275
26
}
276
277
void emit_module(std::ostream& out, const EmissionNode& node,
278
13
                 const std::map<std::string, std::string>& cell_aliases) {
279
13
    const auto& module = *node.module;
280
13
    validate_structural(module);
281
13
    out << "module " << identifier(node.emitted_name) << " (";
282
42
    for (std::size_t i = 0; i < module.get_ports().size(); ++i) {
283
29
        if (i) out << ", ";
284
29
        out << identifier(module.get_ports()[i].get_name());
285
29
    }
286
13
    out << ");\n";
287
29
    for (const auto& port : module.get_ports()) {
288
29
        const char* direction = "inout";
289
29
        switch (port.get_direction()) {
290
19
            case PortDirection::Input: direction = "input"; break;
291
10
            case PortDirection::Output: direction = "output"; break;
292
0
            case PortDirection::InOut: break;
293
29
        }
294
29
        out << "  " << direction << " wire"
295
29
            << range(port.get_packed_width(), port.get_left_index(),
296
29
                     port.get_right_index()) << " "
297
29
            << identifier(port.get_name());
298
29
        if (port.get_unpacked_left_index() &&
299
29
            port.get_unpacked_right_index()) {
300
4
            out << " [" << *port.get_unpacked_left_index() << ":"
301
4
                << *port.get_unpacked_right_index() << "]";
302
4
        }
303
29
        out << ";\n";
304
29
    }
305
13
    for (const auto& declaration : internal_declarations(module)) {
306
1
        out << "  " << declaration << "\n";
307
1
    }
308
13
    for (const auto& assignment : module.get_assignments()) {
309
4
        out << "  assign " << assignment.get_lhs() << " = "
310
4
            << assignment.get_rhs() << ";\n";
311
4
    }
312
108
    for (const auto& instance : module.get_instances()) {
313
108
        auto type = node.child_types.find(instance.get_name());
314
108
        std::string cell_type = type == node.child_types.end()
315
108
                                    ? instance.get_cell_type()
316
108
                                    : type->second;
317
108
        if (type == node.child_types.end()) {
318
104
            const auto alias = cell_aliases.find(cell_type);
319
104
            if (alias != cell_aliases.end()) cell_type = alias->second;
320
104
        }
321
108
        emit_instance(out, instance, cell_type);
322
108
    }
323
13
    out << "endmodule\n\n";
324
13
}
325
326
9
std::vector<EmissionNode> collect_nodes(const Module& root) {
327
9
    std::vector<EmissionNode> nodes;
328
9
    std::unordered_set<const Module*> active;
329
9
    std::size_t serial = 0;
330
9
    const auto visit = [&](const auto& self, const Module& module,
331
13
                           const std::string& emitted_name) -> void {
332
13
        if (!active.insert(&module).second) {
333
0
            throw std::runtime_error("recursive hierarchy cannot be written as Verilog");
334
0
        }
335
13
        EmissionNode node{&module, emitted_name, {}};
336
13
        for (const auto& child : module.get_child_modules()) {
337
4
            std::string child_name = child.get_name() + "__labneura_inst_" +
338
4
                                     std::to_string(serial++);
339
4
            node.child_types.emplace(child.get_hierarchy_instance_name(),
340
4
                                     child_name);
341
4
            self(self, child, child_name);
342
4
        }
343
13
        nodes.push_back(std::move(node));
344
13
        active.erase(&module);
345
13
    };
346
9
    visit(visit, root, root.get_name());
347
9
    return nodes;
348
9
}
349
350
9
void emit_verilog(std::ostream& output, const Module& module) {
351
9
    const auto nodes = collect_nodes(module);
352
9
    std::unordered_set<std::string> hierarchy_types;
353
13
    for (const auto& node : nodes) {
354
13
        for (const auto& [instance, type] : node.child_types) {
355
4
            (void)instance;
356
4
            hierarchy_types.insert(type);
357
4
        }
358
13
    }
359
9
    std::map<std::string, std::string> cell_aliases;
360
9
    std::map<std::string, std::vector<std::string>> cell_pins;
361
13
    for (const auto& node : nodes) {
362
108
        for (const auto& instance : node.module->get_instances()) {
363
108
            if (node.child_types.count(instance.get_name()) ||
364
108
                is_gate_primitive(instance.get_cell_type()) ||
365
108
                hierarchy_types.count(instance.get_cell_type())) {
366
6
                continue;
367
6
            }
368
102
            auto [alias, inserted] = cell_aliases.emplace(
369
102
                instance.get_cell_type(), cell_module_alias(instance.get_cell_type()));
370
102
            (void)inserted;
371
102
            auto& pins = cell_pins[alias->second];
372
209
            for (const auto& connection : instance.get_connections()) {
373
209
                if (std::find(pins.begin(), pins.end(), connection.get_pin()) ==
374
209
                    pins.end()) {
375
10
                    pins.push_back(connection.get_pin());
376
10
                }
377
209
            }
378
102
        }
379
13
    }
380
13
    for (const auto& node : nodes) emit_module(output, node, cell_aliases);
381
9
    for (const auto& [type, alias] : cell_aliases) {
382
4
        const auto& pins = cell_pins[alias];
383
4
        output << "(* blackbox *) module " << identifier(alias) << " (";
384
14
        for (std::size_t i = 0; i < pins.size(); ++i) {
385
10
            if (i) output << ", ";
386
10
            output << identifier(pins[i]);
387
10
        }
388
4
        output << ");\n";
389
10
        for (const auto& pin : pins) {
390
10
            output << "  " << (output_pin_name(pin) ? "output" : "input")
391
10
                   << " wire " << identifier(pin) << ";\n";
392
10
        }
393
4
        output << "endmodule\n\n";
394
4
        (void)type;
395
4
    }
396
9
    if (!output) throw std::runtime_error("failed while writing Verilog netlist");
397
9
}
398
399
14
void validate_verilog_tree(const Module& module) {
400
14
    validate_structural(module);
401
14
    for (const auto& child : module.get_child_modules()) {
402
4
        validate_verilog_tree(child);
403
4
    }
404
14
}
405
406
}  // namespace
407
408
1
std::string to_verilog(const Module& module) {
409
1
    validate_verilog_tree(module);
410
1
    std::ostringstream output;
411
1
    emit_verilog(output, module);
412
1
    return output.str();
413
1
}
414
415
9
void write_verilog(const Module& module, const std::string& path) {
416
9
    validate_verilog_tree(module);
417
9
    std::ofstream output(path);
418
9
    if (!output) throw std::runtime_error("cannot open Verilog output: " + path);
419
9
    emit_verilog(output, module);
420
9
}
421
422
}  // namespace labneura::eda