SILICON
Loading...
Searching...
No Matches
document_conversion.cpp
Go to the documentation of this file.
1/*
2 Copyright (c) 2026. Giulio Cocconi
3
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>.
16 */
17
19
20#include <format>
21#include <map>
22#include <ranges>
23#include <stdexcept>
24#include <unordered_set>
25#include <utility>
26
28#include <core/memory.hpp>
33#include <core/sourceFile.hpp>
34
36namespace {
37
40
41 struct YosysDesign {
42 std::string json;
44 };
45
46 [[nodiscard]] std::string withCircuitModuleNames(std::string json)
47 {
48 auto design = SILICON::yosys::Json::parse(json);
49 auto& modules = design.at("modules");
50 std::unordered_set<std::string> reserved;
51 std::map<std::string, std::string> replacements;
52 for (const auto& [name, _module] : modules.items()) {
53 reserved.insert(name);
55 continue;
56 std::string candidate = name;
57 for (char& c : candidate)
58 if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')
59 || c == '_'))
60 c = '_';
61 if (candidate.empty())
62 candidate = "module";
63 if (candidate.front() >= '0' && candidate.front() <= '9')
64 candidate.insert(0, "module_");
65 replacements.emplace(name, std::move(candidate));
66 }
67 if (replacements.empty())
68 return json;
69
70 // Allocate in name order so suffixes are stable across JSON object orderings.
71 for (auto& [_name, replacement] : replacements) {
72 const auto base = replacement;
73 for (std::size_t suffix = 2; reserved.contains(replacement); ++suffix)
74 replacement = std::format("{}_{}", base, suffix);
75 reserved.insert(replacement);
76 }
77 for (auto& module : modules)
78 for (auto& cell : module.at("cells"))
79 if (const auto replacement =
80 replacements.find(cell.at("type").get<std::string>());
81 replacement != replacements.end())
82 cell["type"] = replacement->second;
83
84 auto renamed = SILICON::yosys::Json::object();
85 for (auto& [name, module] : modules.items()) {
86 const auto replacement = replacements.find(name);
87 renamed[replacement == replacements.end() ? name : replacement->second] =
88 std::move(module);
89 }
90 modules = std::move(renamed);
91 return design.dump();
92 }
93
95 prepareCircuitToVerilog(const Document& source,
96 const std::span<const Document> projectDocuments,
98 const SILICON::core::CircuitResolver& resolver)
99 {
100 const auto slug = SILICON::project::documentSlugForPath(source.getPath());
101 if (source.getType() != DocumentType::Circuit || !slug)
102 throw std::invalid_argument("Only circuits can be converted to Verilog");
103
104 auto circuit = SILICON::core::deserializeCircuitDocument(source.getContents(),
105 registry, &resolver);
106 for (const auto& [component, vertex] : circuit.getComponentToVertex()) {
107 const auto rom = std::dynamic_pointer_cast<SILICON::core::ROM>(
108 circuit.getComponentByVertexId(vertex));
109 if (!rom)
110 continue;
111 const auto slug = rom->getPropertyValue<std::string>("binaryContents");
112 std::shared_ptr<const std::string> snapshot;
113 if (slug) {
114 const auto path = SILICON::project::documentPathForSlug(DocumentType::RawBinary, *slug);
115 for (const auto& document : projectDocuments)
116 if (document.getPath() == path)
117 snapshot = std::make_shared<const std::string>(document.getContents());
118 }
119 rom->refreshBinaryContents(std::move(snapshot));
120 }
121
122 const auto path = SILICON::project::documentPathForSlug(DocumentType::Verilog, *slug);
123 return {
124 .choices = {},
125 .execute =
126 [path, slug = *slug,
127 circuit = std::move(circuit)](const std::span<const std::string> selected) {
128 if (!selected.empty())
129 throw std::invalid_argument(
130 "Circuit-to-Verilog conversion does not accept selections");
131 std::vector<SemanticDocument> documents;
132 documents.push_back(
133 {.path = path,
134 .payload = VerilogSource{.contents =
135 SILICON::verilog::write(circuit, slug)}});
136 return SemanticConversionResult{.documents = std::move(documents),
137 .activatePath = path};
138 },
139 };
140 }
141
143 prepareVerilogToCircuits(const Document& source,
144 const std::span<const Document> projectDocuments)
145 {
146 if (source.getType() != DocumentType::Verilog)
147 throw std::invalid_argument("Only Verilog files can be converted to circuits");
148
149 std::vector<SILICON::core::SourceFile> sources;
150 for (const auto& document : projectDocuments) {
151 if (document.getType() == DocumentType::Verilog)
152 sources.push_back(
153 {.path = document.getPath(), .contents = document.getContents()});
154 }
155
156 YosysDesign design{
157 .json = withCircuitModuleNames(SILICON::yosys::elaborateHierarchy(
158 SILICON::verilog::read(sources, source.getPath()))),
159 .modules = {},
160 };
161 design.modules = SILICON::yosys::moduleDependencyGraph(design.json);
162 if (design.modules.modules().empty())
163 throw std::runtime_error("Verilog source must declare at least one module");
164
165 const auto allModules = design.modules.modules();
166 static_cast<void>(design.modules.dependencyOrder(allModules));
167
168 std::vector<ConversionChoice> choices;
169 choices.reserve(allModules.size());
170 for (const auto& module : allModules) {
171 choices.push_back({.id = module,
172 .label = module,
173 .dependencies = design.modules.dependenciesOf(module)});
174 }
175
176 return {
177 .choices = std::move(choices),
178 .execute =
179 [design = std::move(design)](const std::span<const std::string> selected) {
180 if (selected.empty())
181 throw std::invalid_argument("At least one module must be selected");
182
183 const std::vector<std::string> roots(selected.begin(), selected.end());
184 const auto exportOrder = design.modules.dependencyOrder(roots);
185
186 std::vector<SemanticDocument> generated;
187 generated.reserve(exportOrder.size());
188 for (const auto& module : exportOrder) {
190 throw std::runtime_error(std::format(
191 "Verilog module '{}' cannot be used as a project circuit name",
192 module));
193 }
194 auto circuit = SILICON::yosys::deserialize(design.json, module);
195 for (const auto& [component, vertex] : circuit.getComponentToVertex()) {
196 const auto rom = std::dynamic_pointer_cast<SILICON::core::ROM>(
197 circuit.getComponentByVertexId(vertex));
198 if (!rom)
199 continue;
200 const auto slug = rom->getPropertyValue<std::string>("binaryContents");
201 const auto contents = rom->binaryContentsSnapshot();
202 if (!slug || !contents)
203 throw std::runtime_error("Imported ROM has no binary contents");
204 const auto path = SILICON::project::documentPathForSlug(DocumentType::RawBinary, *slug);
205 const auto existing = std::ranges::find_if(generated, [&](const SemanticDocument& item) { return item.path == path; });
206 if (existing == generated.end())
207 generated.push_back({.path = path, .payload = BinarySource{*contents}});
208 else if (std::get<BinarySource>(existing->payload).contents != *contents)
209 throw std::runtime_error("Conflicting ROM binary document names");
210 }
211 generated.push_back({
212 .path = SILICON::project::documentPathForSlug(DocumentType::Circuit,
213 module),
214 .payload = std::move(circuit),
215 });
216 }
217
219 .documents = std::move(generated),
221 DocumentType::Circuit, roots.front()),
222 };
223 },
224 };
225 }
226
227} // namespace
228
231 const std::span<const Document> projectDocuments,
232 const SILICON::core::ComponentRegistry& registry,
233 const SILICON::core::CircuitResolver& resolver)
234{
235 if (source.getType() == DocumentType::Circuit && target == DocumentType::Verilog)
236 return prepareCircuitToVerilog(source, projectDocuments, registry, resolver);
237 if (source.getType() == DocumentType::Verilog && target == DocumentType::Circuit)
238 return prepareVerilogToCircuits(source, projectDocuments);
239 throw std::invalid_argument("The selected document has no registered conversion");
240}
241
242} // namespace SILICON::conversion
Module-instantiation dependency graph for a Yosys JSON design.
Definition netlist.hpp:58
ModuleNameList dependencyOrder(const ModuleNameList &roots) const
Returns the unique dependency closure of roots in dependency-first order.
ModuleNameList dependenciesOf(std::string_view moduleName) const
Returns the sorted, unique modules moduleName instantiates.
ModuleNameList modules() const
Returns every declared module name.
PreparedSemanticConversion prepareDocumentConversion(const Document &source, const DocumentType target, const std::span< const Document > projectDocuments, const SILICON::core::ComponentRegistry &registry, const SILICON::core::CircuitResolver &resolver)
Circuit deserializeCircuitDocument(const std::string_view contents, const ComponentRegistry &registry, const CircuitResolver *resolver)
std::string documentPathForSlug(const DocumentType type, const std::string_view slug)
std::optional< std::string > documentSlugForPath(const std::string_view path)
bool isValidDocumentSlug(const std::string_view slug)
std::string write(const std::string_view yosysJson, const yosys::ToolOptions &options)
Definition verilog.cpp:494
std::string read(const std::string_view source, const yosys::ToolOptions &options)
Definition verilog.cpp:477
std::string elaborateHierarchy(const std::string_view json, const ToolOptions &options)
Circuit deserialize(const std::string_view json, const std::optional< std::string_view > moduleName)
Deserialize one supported Yosys write_json module into a Silicon circuit.
ModuleDependencyGraph moduleDependencyGraph(const std::string_view json)
Build a module dependency graph from a Yosys write_json document.