59#include <nlohmann/json.hpp>
69class YosysLogCapture {
72 : handle(Logger::addCallbackSink([this](const LogMessage& message) {
73 if (message.category ==
"yosys")
74 messages.push_back(message);
81 [[nodiscard]] std::string text()
const
84 for (
const auto& message : messages)
85 result += message.message +
'\n';
90 std::vector<LogMessage> messages;
94class DefaultedInputYosysComponent :
public Component {
98 defineUnconnectedInputDefault(0, State::HIGH);
101 std::string_view typeName()
const override {
return "DefaultedInputYosys"; }
102 void simulate(Simulator&)
override {}
104 void serializeYosys(SILICON::yosys::SerializationContext& context)
const override
107 using SILICON::yosys::SerializationContext;
108 context.
addCell(
"default_input",
"$pos",
112 Json{{
"A",
"input"}, {
"Y",
"output"}},
114 {
"Y", context.
bits(outputBuses().at(0))}});
118#if !defined(_WIN32) && !defined(__EMSCRIPTEN__)
119class PathEnvironmentGuard {
121 PathEnvironmentGuard()
123 if (
const char* value = std::getenv(
"PATH"))
125 setenv(
"PATH",
"", 1);
128 ~PathEnvironmentGuard()
131 setenv(
"PATH", original->c_str(), 1);
137 std::optional<std::string> original;
144[[nodiscard]]
inline Circuit importVerilog(
const std::string_view source,
145 const std::string_view topModule,
154[[nodiscard]]
inline std::string legalizeExpressions(std::string_view rawJson,
155 std::string_view passes =
"silicon_logic\nsilicon_compare\nsilicon_shift")
157#ifdef SILICON_TEST_YOSYS_PLUGIN_AVAILABLE
158 const auto directory = std::filesystem::temp_directory_path()
159 / std::format(
"silicon_expression_{}",
160 std::chrono::steady_clock::now().time_since_epoch().count());
161 std::filesystem::create_directories(directory);
162 const auto input = directory /
"input.json";
163 const auto output = directory /
"output.json";
165 { std::ofstream file(input); file << rawJson; }
167 "plugin -i \"{}\"\nread_json \"{}\"\n{}\nwrite_json \"{}\"",
168 SILICON_TEST_YOSYS_PLUGIN_PATH, input.string(), passes, output.string()));
169 std::ifstream file(output);
170 std::string result((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
171 std::filesystem::remove_all(directory);
174 std::filesystem::remove_all(directory);
178 return std::string(rawJson);
182[[nodiscard]]
inline nlohmann::json exportComponent(
const Component_ptr& component)
184 Circuit circuit(component,
false);
188[[nodiscard]]
inline nlohmann::json signalBits(
int& nextSignal,
const std::size_t width)
190 auto bits = nlohmann::json::array();
191 for (std::size_t bit = 0; bit <
width; ++bit)
192 bits.push_back(nextSignal++);
196[[nodiscard]]
inline nlohmann::json subtractionDesign(
const std::size_t aWidth,
197 const std::size_t bWidth,
198 const std::size_t yWidth,
199 const bool aSigned,
const bool bSigned)
205 const Json aBits = signalBits(nextSignal, aWidth);
206 const Json bBits = signalBits(nextSignal, bWidth);
207 const Json yBits = signalBits(nextSignal, yWidth);
208 const Json parameters{
216 return Json{{
"creator",
"test"},
219 {{
"attributes", Json::object()},
221 {{
"a", {{
"direction",
"input"}, {
"bits", aBits}}},
222 {
"b", {{
"direction",
"input"}, {
"bits", bBits}}},
223 {
"y", {{
"direction",
"output"}, {
"bits", yBits}}}}},
227 {
"parameters", parameters},
228 {
"connections", {{
"A", aBits}, {
"B", bBits}, {
"Y", yBits}}}}}}},
229 {
"netnames", Json::object()}}}}}};
232[[nodiscard]]
inline nlohmann::json comparisonDesign(
const std::string_view type,
233 const std::size_t aWidth,
234 const std::size_t bWidth,
235 const std::size_t yWidth,
236 const bool aSigned,
const bool bSigned)
242 const Json aBits = signalBits(nextSignal, aWidth);
243 const Json bBits = signalBits(nextSignal, bWidth);
244 const Json yBits = signalBits(nextSignal, yWidth);
246 return Json{{
"creator",
"test"},
249 {{
"attributes", Json::object()},
251 {{
"a", {{
"direction",
"input"}, {
"bits", aBits}}},
252 {
"b", {{
"direction",
"input"}, {
"bits", bBits}}},
253 {
"y", {{
"direction",
"output"}, {
"bits", yBits}}}}},
263 {
"connections", {{
"A", aBits}, {
"B", bBits}, {
"Y", yBits}}}}}}},
264 {
"netnames", Json::object()}}}}}};
267[[nodiscard]]
inline BusValue evaluateBinaryCircuit(
const std::shared_ptr<Circuit>& circuit,
268 const unsigned int a,
const unsigned int b)
270 std::map<std::string, std::shared_ptr<DummyBusInputComponent>> inputs;
272 for (
const auto vertex :
273 boost::make_iterator_range(boost::vertices(circuit->getGraph()))) {
274 const auto& component = circuit->getGraph()[vertex].component;
275 if (
auto input = std::dynamic_pointer_cast<DummyBusInputComponent>(component))
276 inputs.emplace(input->getPropertyValue<std::string>(
"name").value_or(
""), input);
277 if (std::dynamic_pointer_cast<DummyOutputComponent>(component)
278 || std::dynamic_pointer_cast<DummyBusOutputComponent>(component))
282 if (!inputs.contains(
"a") || !inputs.contains(
"b") || !output)
283 throw std::runtime_error(
"Expected named binary circuit boundary components");
284 inputs.at(
"a")->setBusValue(
valueFor(inputs.at(
"a")->outputBuses()[0], a));
285 inputs.at(
"b")->setBusValue(
valueFor(inputs.at(
"b")->outputBuses()[0], b));
288 throw std::runtime_error(
"Binary circuit simulation did not complete");
289 return output->inputBuses()[0].getCurrentValue();
292[[nodiscard]]
inline std::multiset<std::string> cellTypes(
const nlohmann::json& module)
294 std::multiset<std::string> result;
295 for (
const auto& cell : module.at(
"cells"))
296 result.insert(cell.at(
"type").get<std::string>());
300template <
typename ComponentType>
301[[nodiscard]]
inline std::shared_ptr<ComponentType>
302findNamedComponent(
const Circuit& circuit,
const std::string_view name)
305 auto candidate = std::dynamic_pointer_cast<ComponentType>(component);
307 && candidate->template getPropertyValue<std::string>(
"name").value_or(
"")
315[[nodiscard]]
inline const nlohmann::json& onlyModule(
const nlohmann::json& design)
317 return design.at(
"modules").begin().value();
320[[nodiscard]]
inline nlohmann::json& onlyModule(nlohmann::json& design)
322 return design.at(
"modules").begin().value();
325[[nodiscard]]
inline const nlohmann::json& onlyCell(
const nlohmann::json& design)
327 return onlyModule(design).at(
"cells").begin().value();
330template <
typename ComponentType>
331[[nodiscard]]
inline std::shared_ptr<ComponentType> findComponent(
const Circuit& circuit)
333 for (
const auto vertex :
334 boost::make_iterator_range(boost::vertices(circuit.
getGraph()))) {
335 if (
auto component = std::dynamic_pointer_cast<ComponentType>(
336 circuit.
getGraph()[vertex].component))
345 for (std::size_t index = 0; index < component->inputBuses().size(); ++index) {
346 components.insert(std::make_shared<DummyBusInputComponent>(
347 component->inputBuses()[index], std::format(
"input_{}", index)));
349 for (std::size_t index = 0; index < component->outputBuses().size(); ++index) {
350 components.insert(std::make_shared<DummyBusOutputComponent>(
351 component->outputBuses()[index], std::format(
"output_{}", index)));
353 Circuit circuit(components,
false);
357[[nodiscard]]
inline std::shared_ptr<Register>
358registerWithMode(
const bool parallelInput,
const bool parallelOutput,
const int width = 4)
360 auto reg = std::make_shared<Register>(
361 Bus(
static_cast<unsigned short>(width)), std::make_shared<Wire>(),
362 std::make_shared<Wire>(), std::make_shared<Wire>(),
363 Bus(
static_cast<unsigned short>(width)));
371#ifdef SILICON_TEST_YOSYS_EXECUTABLE
372[[nodiscard]]
inline int validateWithYosys(
const Circuit& circuit,
const std::string_view tag)
375 std::filesystem::temp_directory_path() / std::format(
"silicon_yosys_{}.json", tag);
377 std::ofstream output(path);
386 .executable = std::filesystem::path(SILICON_TEST_YOSYS_EXECUTABLE),
387 .technologyLibraryDirectory = std::nullopt};
389 std::format(
"read_verilog -lib -D SILICON_BLACKBOX \"{}/silicon_cells.v\"\n"
391 "hierarchy -check -top top\n"
393 SILICON_TEST_YOSYS_RESOURCE_DIR, path.string()),
395 }
catch (
const std::runtime_error&) {
398 std::filesystem::remove(path);
402#ifdef SILICON_TEST_YOSYS_PLUGIN_PATH
403inline void runPluginScript(
const std::string_view source,
const std::string_view commands,
404 const std::string_view tag)
407 std::filesystem::temp_directory_path()
408 / std::format(
"silicon_yosys_{}_{}.v", tag,
409 std::chrono::steady_clock::now().time_since_epoch().count());
411 std::ofstream output(path);
413 throw std::runtime_error(
"Could not create temporary Verilog source");
419 .executable = std::filesystem::path(SILICON_TEST_YOSYS_EXECUTABLE),
420 .technologyLibraryDirectory = std::nullopt};
422 std::format(
"plugin -i \"{}\"\nread_verilog \"{}\"\n{}",
423 SILICON_TEST_YOSYS_PLUGIN_PATH, path.string(), commands),
426 std::filesystem::remove(path);
429 std::filesystem::remove(path);
std::vector< Component_ptr > componentsIn(const Circuit &circuit)
Represents a digital circuit as a directed graph of components.
const CircuitGraph & getGraph() const
Gets the underlying circuit graph.
Base class for all digital circuit components.
static constexpr std::string_view SERIAL_TYPE
static constexpr std::string_view PARALLEL_TYPE
static void removeSink(SinkHandle handle)
Executes event-driven simulation of a Circuit.
Mutable module-building interface passed to component serializers.
Json bits(const core::Bus &bus, std::string_view nullValue="x") const
Convert a Silicon bus to a Yosys least-significant-bit-first vector.
static std::string parameter(std::uint64_t value, std::size_t width=32)
Encode an unsigned Yosys parameter as a fixed-width binary string.
Json inputBits(const core::Component &component, std::size_t index, std::size_t expectedWidth) const
Encode a component input, applying its declared unconnected-input default.
void addCell(std::string_view suffix, std::string_view type, Json parameters, Json portDirections, Json connections, Json attributes=Json::object())
Emit one native Yosys cell for the current Silicon component.
int width(RTLIL::Module *module, RTLIL::Cell *cell, RTLIL::IdString key)
std::shared_ptr< Component > Component_ptr
std::shared_ptr< Wire > Wire_ptr
std::set< Component_ptr, std::owner_less< Component_ptr > > Component_set
std::vector< State > BusValue
QVariant value(const QSettings &settings, const Definition &setting)
Reads a setting value, falling back to its declared default when unset.
std::string read(const std::string_view source, const yosys::ToolOptions &options)
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.
ScriptResult runScript(const std::string_view script, const ToolOptions &options)
std::string serialize(const Circuit &circuit, const std::string_view moduleName)
Serialize a complete Silicon circuit as Yosys write_json-compatible JSON.
nlohmann::ordered_json Json
BusValue valueFor(const Bus &bus, const std::uint64_t value)