SILICON
Loading...
Searching...
No Matches
subcircuit.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#include "tests.hpp"
20
21#include <chrono>
22#include <cstdint>
23#include <filesystem>
24#include <format>
25#include <memory>
26#include <optional>
27#include <set>
28#include <string>
29#include <string_view>
30#include <utility>
31#include <vector>
32
33#include <core/circuit.hpp>
35#include <core/elaboration.hpp>
36#include <core/gates.hpp>
37#include <core/io.hpp>
38#include <core/memory.hpp>
47#include <core/simulator.hpp>
48#include <core/subcircuit.hpp>
49
50#include <nlohmann/json.hpp>
51
52using namespace SILICON::core;
53using namespace SILICON::project;
54using namespace SILICON::simulation;
55using namespace SILICON::waveform;
56
57namespace {
58
59std::string graphicalAndSubcircuitDocument()
60{
61 return R"({
62 "circuit": {
63 "version": "0.1.0",
64 "name": "graphical_and_subcircuit",
65 "components": [
66 {
67 "id": 0,
68 "type": "DummyInputComponent",
69 "properties": {"name": "a", "portOrientation": "DOWN", "startValue": "0"},
70 "inputs": [],
71 "outputs": [[1]]
72 },
73 {
74 "id": 1,
75 "type": "DummyInputComponent",
76 "properties": {"name": "b", "portOrientation": "DOWN", "startValue": "0"},
77 "inputs": [],
78 "outputs": [[2]]
79 },
80 {
81 "id": 2,
82 "type": "AndGate",
83 "properties": {"delay": 0, "bitwise": false, "size": 1},
84 "inputs": [[1], [2]],
85 "outputs": [[3]]
86 },
87 {
88 "id": 3,
89 "type": "DummyOutputComponent",
90 "properties": {"name": "q", "portOrientation": "DOWN"},
91 "inputs": [[3]],
92 "outputs": []
93 }
94 ]
95 },
96 "visual": {
97 "components": [
98 {"type": "Input", "vertexId": 0, "position": {"x": 0, "y": 0}},
99 {"type": "Input", "vertexId": 1, "position": {"x": 0, "y": 80}},
100 {"type": "AndGate", "vertexId": 2, "position": {"x": 120, "y": 40}},
101 {"type": "Output", "vertexId": 3, "position": {"x": 240, "y": 40}}
102 ],
103 "wires": []
104 },
105 "graphicalComponent": {
106 "shape": {"type": "rectangle", "width": 8, "height": 8},
107 "inputs": [],
108 "outputs": []
109 }
110 })";
111}
112
113std::string graphicalBusSubcircuitDocument()
114{
115 return R"({
116 "circuit": {
117 "version": "0.1.0",
118 "name": "graphical_bus_subcircuit",
119 "components": [
120 {
121 "id": 0,
122 "type": "DummyBusInputComponent",
123 "properties": {"name": "data", "size": 8, "portOrientation": "DOWN", "startValue": "00000000"},
124 "inputs": [],
125 "outputs": [[1, 2, 3, 4, 5, 6, 7, 8]]
126 },
127 {
128 "id": 1,
129 "type": "NotGate",
130 "properties": {"delay": 0, "bitwise": true, "size": 8},
131 "inputs": [[1, 2, 3, 4, 5, 6, 7, 8]],
132 "outputs": [[9, 10, 11, 12, 13, 14, 15, 16]]
133 },
134 {
135 "id": 2,
136 "type": "DummyBusOutputComponent",
137 "properties": {"name": "result", "size": 8, "portOrientation": "DOWN"},
138 "inputs": [[9, 10, 11, 12, 13, 14, 15, 16]],
139 "outputs": []
140 }
141 ]
142 },
143 "visual": {"components": [], "wires": []},
144 "graphicalComponent": {
145 "shape": {"type": "rectangle", "width": 8, "height": 8},
146 "inputs": [],
147 "outputs": []
148 }
149 })";
150}
151
152std::string busNotCoreDocument()
153{
154 return R"({
155 "circuit": {
156 "version": "0.1.0",
157 "name": "bus_not_core",
158 "components": [
159 {
160 "id": 0,
161 "type": "NotGate",
162 "properties": {"delay": 0, "bitwise": true, "size": 8},
163 "inputs": [[1, 2, 3, 4, 5, 6, 7, 8]],
164 "outputs": [[9, 10, 11, 12, 13, 14, 15, 16]]
165 }
166 ]
167 }
168})";
169}
170
171std::string delayedNotSubcircuitDocument()
172{
173 return R"({
174 "circuit": {
175 "version": "0.1.0",
176 "name": "delayed_not",
177 "components": [
178 {
179 "id": 0,
180 "type": "NotGate",
181 "properties": {"delay": 2},
182 "inputs": [[1]],
183 "outputs": [[2]]
184 }
185 ]
186 }
187})";
188}
189
190std::string doubleNotSubcircuitDocument()
191{
192 return R"({
193 "circuit": {
194 "version": "0.1.0",
195 "name": "double_not",
196 "components": [
197 {
198 "id": 0,
199 "type": "NotGate",
200 "properties": {"delay": 0},
201 "inputs": [[1]],
202 "outputs": [[2]]
203 },
204 {
205 "id": 1,
206 "type": "NotGate",
207 "properties": {"delay": 0},
208 "inputs": [[2]],
209 "outputs": [[3]]
210 }
211 ]
212 }
213 })";
214}
215
216std::string nestedAndSubcircuitDocument()
217{
218 return R"({
219 "circuit": {
220 "version": "0.1.0",
221 "name": "nested_and",
222 "components": [
223 {
224 "id": 0,
225 "type": "Subcircuit",
226 "properties": {"slug": "and_gate"},
227 "inputs": [[1], [2]],
228 "outputs": [[3]]
229 }
230 ]
231 }
232 })";
233}
234
235std::string romSubcircuitDocument()
236{
237 return R"({
238 "circuit": {
239 "version": "0.1.0",
240 "name": "rom_leaf",
241 "components": [
242 {
243 "id": 0,
244 "type": "ROM",
245 "properties": {"dataWidth": 8, "binaryContents": "program"},
246 "inputs": [[1, 2], [3], [4]],
247 "outputs": [[5, 6, 7, 8, 9, 10, 11, 12]]
248 }
249 ]
250 }
251 })";
252}
253
254std::string nestedRomSubcircuitDocument()
255{
256 return R"({
257 "circuit": {
258 "version": "0.1.0",
259 "name": "rom_parent",
260 "components": [
261 {
262 "id": 0,
263 "type": "Subcircuit",
264 "properties": {"slug": "rom_leaf"},
265 "inputs": [],
266 "outputs": []
267 }
268 ]
269 }
270 })";
271}
272
273std::string romSimulationLeafDocument()
274{
275 return R"({
276 "circuit": {
277 "version": "0.1.0",
278 "name": "rom_sim_leaf",
279 "components": [
280 {
281 "id": 0,
282 "type": "DummyBusInputComponent",
283 "properties": {"name": "address", "size": 2, "portOrientation": "DOWN", "startValue": "00"},
284 "inputs": [],
285 "outputs": [[1, 2]]
286 },
287 {
288 "id": 1,
289 "type": "DummyInputComponent",
290 "properties": {"name": "cs", "portOrientation": "DOWN", "startValue": "0"},
291 "inputs": [],
292 "outputs": [[3]]
293 },
294 {
295 "id": 2,
296 "type": "DummyInputComponent",
297 "properties": {"name": "oe", "portOrientation": "DOWN", "startValue": "0"},
298 "inputs": [],
299 "outputs": [[4]]
300 },
301 {
302 "id": 3,
303 "type": "ROM",
304 "properties": {"dataWidth": 8, "binaryContents": "program"},
305 "inputs": [[1, 2], [3], [4]],
306 "outputs": [[5, 6, 7, 8, 9, 10, 11, 12]]
307 },
308 {
309 "id": 4,
310 "type": "DummyBusOutputComponent",
311 "properties": {"name": "data", "size": 8, "portOrientation": "DOWN"},
312 "inputs": [[5, 6, 7, 8, 9, 10, 11, 12]],
313 "outputs": []
314 }
315 ]
316 }
317 })";
318}
319
320std::string romSimulationParentDocument()
321{
322 return R"({
323 "circuit": {
324 "version": "0.1.0",
325 "name": "rom_sim_parent",
326 "components": [
327 {
328 "id": 0,
329 "type": "DummyBusInputComponent",
330 "properties": {"name": "address", "size": 2, "portOrientation": "DOWN", "startValue": "00"},
331 "inputs": [],
332 "outputs": [[1, 2]]
333 },
334 {
335 "id": 1,
336 "type": "DummyInputComponent",
337 "properties": {"name": "cs", "portOrientation": "DOWN", "startValue": "0"},
338 "inputs": [],
339 "outputs": [[3]]
340 },
341 {
342 "id": 2,
343 "type": "DummyInputComponent",
344 "properties": {"name": "oe", "portOrientation": "DOWN", "startValue": "0"},
345 "inputs": [],
346 "outputs": [[4]]
347 },
348 {
349 "id": 3,
350 "type": "Subcircuit",
351 "properties": {"slug": "rom_sim_leaf"},
352 "inputs": [[1, 2], [3], [4]],
353 "outputs": [[5, 6, 7, 8, 9, 10, 11, 12]]
354 },
355 {
356 "id": 4,
357 "type": "DummyBusOutputComponent",
358 "properties": {"name": "data", "size": 8, "portOrientation": "DOWN"},
359 "inputs": [[5, 6, 7, 8, 9, 10, 11, 12]],
360 "outputs": []
361 }
362 ]
363 }
364 })";
365}
366
367class RecursiveCircuitResolver final : public CircuitResolver {
368public:
369 [[nodiscard]] SubcircuitDefinition resolve(const std::string_view slug) const override
370 {
371 const auto nestedSlug = slug == "a" ? "b" : "a";
372 auto nested = SubcircuitComponent::imported(nestedSlug, {}, {}, {}, {});
373 return {Circuit(nested, false), {}, {}};
374 }
375};
376
377std::string feedbackLatchCoreDocument()
378{
379 return R"({
380 "circuit": {
381 "version": "0.1.0",
382 "name": "feedback_latch",
383 "components": [
384 {
385 "id": 0,
386 "type": "NorGate",
387 "properties": {"delay": 0, "bitwise": false, "size": 1},
388 "inputs": [[778], [776]],
389 "outputs": [[777]]
390 },
391 {
392 "id": 1,
393 "type": "NorGate",
394 "properties": {"delay": 0, "bitwise": false, "size": 1},
395 "inputs": [[777], [779]],
396 "outputs": [[776]]
397 },
398 {
399 "id": 2,
400 "type": "DummyInputComponent",
401 "properties": {"name": "set", "portOrientation": "DOWN", "startValue": "0"},
402 "inputs": [],
403 "outputs": [[778]]
404 },
405 {
406 "id": 3,
407 "type": "DummyInputComponent",
408 "properties": {"name": "reset", "portOrientation": "DOWN", "startValue": "0"},
409 "inputs": [],
410 "outputs": [[779]]
411 },
412 {
413 "id": 4,
414 "type": "DummyOutputComponent",
415 "properties": {"name": "q", "portOrientation": "DOWN"},
416 "inputs": [[777]],
417 "outputs": []
418 },
419 {
420 "id": 5,
421 "type": "DummyOutputComponent",
422 "properties": {"name": "not_q", "portOrientation": "DOWN"},
423 "inputs": [[776]],
424 "outputs": []
425 }
426 ]
427 }
428 })";
429}
430
431class SubcircuitTest : public ::testing::Test {
432protected:
433 void SetUp() override
434 {
435 registerAllComponents(registry);
438 }
439
440 ComponentRegistry registry = ComponentRegistry::empty();
441 SILICON::project::ProjectContext project;
442 SILICON::project::ProjectCircuitResolver resolver{project, registry};
443};
444
445SILICON::project::Document subcircuitDocument(std::string slug, std::string sceneJson)
446{
448 slug),
449 std::move(sceneJson)};
450}
451
452struct ProjectFileCleanup {
453 std::filesystem::path path;
454 ~ProjectFileCleanup() { std::filesystem::remove(path); }
455};
456
457std::filesystem::path temporaryProjectPath()
458{
459 const auto stamp = std::chrono::steady_clock::now().time_since_epoch().count();
460 return std::filesystem::temp_directory_path()
461 / std::format("silicon_subcircuit_resolver_{}.sil", stamp);
462}
463
464} // namespace
465
466TEST_F(SubcircuitTest, DeserializesSubcircuitSlugProperty)
467{
468 project.upsertDocument(subcircuitDocument("and_gate", andSubcircuitDocument()));
469
470 const auto json = R"({
471 "version": "0.1.0",
472 "name": "main",
473 "components": [
474 {
475 "id": 0,
476 "type": "Subcircuit",
477 "properties": {"slug": "and_gate"},
478 "inputs": [[10], [11]],
479 "outputs": [[12]]
480 }
482 })";
483
484 auto circuit = Circuit::deserialize(json, ComponentRegistry::instance(), &resolver);
485 auto component = circuit.getComponentByVertexId(0);
486 ASSERT_NE(component, nullptr);
487 EXPECT_EQ(component->typeName(), SubcircuitComponent::Type);
488 EXPECT_EQ(component->getPropertyValue<std::string>("slug"), "and_gate");
489 EXPECT_EQ(component->getInputs().size(), 2);
490 EXPECT_EQ(component->getOutputs().size(), 1);
491}
492
493TEST_F(SubcircuitTest, DeserializesSubcircuitWithMissingSavedOutputs)
494{
495 project.upsertDocument(
496 subcircuitDocument("graphical_and", graphicalAndSubcircuitDocument()));
497
498 const auto json = R"({
499 "version": "0.1.0",
500 "name": "main",
501 "components": [
502 {
503 "id": 0,
504 "type": "Subcircuit",
505 "properties": {"slug": "graphical_and"},
506 "inputs": [[10], [11]],
507 "outputs": []
508 }
509 ]
510 })";
511
512 auto circuit = Circuit::deserialize(json, ComponentRegistry::instance(), &resolver);
513 auto component = circuit.getComponentByVertexId(0);
514
515 ASSERT_NE(component, nullptr);
516 EXPECT_EQ(component->getInputs().size(), 2);
517 ASSERT_EQ(component->getOutputs().size(), 1);
518 EXPECT_EQ(component->getOutputs()[0].size(), 1);
519
520 const auto serialized = nlohmann::json::parse(circuit.serialize());
521 ASSERT_EQ(serialized["components"].size(), 1);
522 EXPECT_EQ(serialized["components"][0]["outputs"].size(), 1);
523}
524
525TEST_F(SubcircuitTest, SimulatesCombinationalSubcircuit)
526{
527 project.upsertDocument(subcircuitDocument("and_gate", andSubcircuitDocument()));
528
529 auto component = std::make_shared<SubcircuitComponent>(&resolver);
530 component->setPropertyValue("slug", std::string("and_gate"));
531
532 auto inputA = std::make_shared<Wire>();
533 auto inputB = std::make_shared<Wire>();
534 auto output = std::make_shared<Wire>();
535 component->setInput(0, Bus{inputA});
536 component->setInput(1, Bus{inputB});
537 component->setOutput(0, Bus{output});
538
539 auto circuit = std::make_shared<Circuit>(component, false);
540 SILICON::simulation::Session simulator(circuit, {}, &resolver);
541
542 EXPECT_EQ(simulator.setBus(Bus{inputA}, valueFor(Bus{inputA}, 1)),
544 EXPECT_EQ(simulator.setBus(Bus{inputB}, valueFor(Bus{inputB}, 1)),
546 EXPECT_EQ(output->getCurrentState(), State::HIGH);
547
548 EXPECT_EQ(simulator.setBus(Bus{inputB}, valueFor(Bus{inputB}, 0)),
550 EXPECT_EQ(output->getCurrentState(), State::LOW);
551}
552
553TEST_F(SubcircuitTest, ElaboratesPrimitiveCircuitWithoutHierarchy)
554{
555 auto input = std::make_shared<Wire>();
556 auto output = std::make_shared<Wire>();
557 auto gate = std::make_shared<NotGate>(input, output);
558 Circuit source(gate, false);
559
561 &resolver);
562 auto runtime = elaborator.elaborate(source);
563
564 ASSERT_EQ(source.getComponentToVertex().size(), 1);
565 ASSERT_EQ(runtime->getComponentToVertex().size(), 1);
566 const auto runtimeComponent = runtime->getComponentToVertex().begin()->first;
567 EXPECT_EQ(runtimeComponent->typeName(), NotGate::Type);
568 EXPECT_NE(runtimeComponent, gate.get());
569 EXPECT_EQ(runtimeComponent->getInputs()[0][0], input);
570 EXPECT_EQ(runtimeComponent->getOutputs()[0][0], output);
571}
572
573TEST_F(SubcircuitTest, RuntimeElaborationLeavesSavedCircuitUnchanged)
574{
575 project.upsertDocument(subcircuitDocument("and_gate", andSubcircuitDocument()));
576
577 const auto json = R"({
578 "version": "0.1.0",
579 "name": "main",
580 "components": [
581 {
582 "id": 0,
583 "type": "Subcircuit",
584 "properties": {"slug": "and_gate"},
585 "inputs": [[10], [11]],
586 "outputs": [[12]]
587 }
588 ]
589 })";
590
591 auto circuit = Circuit::deserialize(json, ComponentRegistry::instance(), &resolver);
593 &resolver);
594 auto elaborated = elaborator.elaborate(circuit);
595
596 const auto savedJson = nlohmann::json::parse(circuit.serialize());
597 ASSERT_EQ(savedJson["components"].size(), 1);
598 EXPECT_EQ(savedJson["components"][0]["type"], SubcircuitComponent::Type);
599
600 const auto runtimeJson = nlohmann::json::parse(elaborated->serialize());
601 ASSERT_EQ(runtimeJson["components"].size(), 1);
602 EXPECT_EQ(runtimeJson["components"][0]["type"], AndGate::Type);
603}
604
605TEST_F(SubcircuitTest, RemapsTwoInstancesOfSameSubcircuitIndependently)
606{
607 project.upsertDocument(subcircuitDocument("not_gate", delayedNotSubcircuitDocument()));
608
609 const auto json = R"({
610 "version": "0.1.0",
611 "name": "main",
612 "components": [
613 {
614 "id": 0,
615 "type": "Subcircuit",
616 "properties": {"slug": "not_gate"},
617 "inputs": [[10]],
618 "outputs": [[11]]
619 },
620 {
621 "id": 1,
622 "type": "Subcircuit",
623 "properties": {"slug": "not_gate"},
624 "inputs": [[20]],
625 "outputs": [[21]]
626 }
627 ]
628 })";
629
630 auto circuit = std::make_shared<Circuit>(
632 auto firstInput = circuit->getComponentByVertexId(0)->getInputs()[0];
633 auto firstOutput = circuit->getComponentByVertexId(0)->getOutputs()[0][0];
634 auto secondInput = circuit->getComponentByVertexId(1)->getInputs()[0];
635 auto secondOutput = circuit->getComponentByVertexId(1)->getOutputs()[0][0];
636
637 SILICON::simulation::Session simulator(circuit, {}, &resolver);
639 EXPECT_EQ(simulator.setBus(firstInput, valueFor(firstInput, 0)),
641 EXPECT_EQ(simulator.setBus(secondInput, valueFor(secondInput, 1)),
643 EXPECT_EQ(simulator.runUntilIdle(), Simulator::RunResult::Completed);
644
645 EXPECT_EQ(firstOutput->getCurrentState(), State::HIGH);
646 EXPECT_EQ(secondOutput->getCurrentState(), State::LOW);
647}
648
649TEST_F(SubcircuitTest, ClonesInternalWiresForEverySubcircuitInstance)
650{
651 project.upsertDocument(subcircuitDocument("double_not", doubleNotSubcircuitDocument()));
652
653 auto first = std::make_shared<SubcircuitComponent>(&resolver);
654 auto second = std::make_shared<SubcircuitComponent>(&resolver);
655 first->setPropertyValue("slug", std::string("double_not"));
656 second->setPropertyValue("slug", std::string("double_not"));
657
658 auto firstInput = std::make_shared<Wire>();
659 auto firstOutput = std::make_shared<Wire>();
660 auto secondInput = std::make_shared<Wire>();
661 auto secondOutput = std::make_shared<Wire>();
662 first->setInput(0, Bus{firstInput});
663 first->setOutput(0, Bus{firstOutput});
664 second->setInput(0, Bus{secondInput});
665 second->setOutput(0, Bus{secondOutput});
666
667 Circuit source(Component_set{first, second}, false);
669 &resolver);
670 auto runtime = elaborator.elaborate(source);
671
672 const std::set<const Wire*> interfaceWires{firstInput.get(), firstOutput.get(),
673 secondInput.get(), secondOutput.get()};
674 std::set<const Wire*> internalWires;
675 for (const auto& [component, _vertex] : runtime->getComponentToVertex()) {
676 for (const auto& bus : component->inputBuses()) {
677 for (const auto& wire : bus) {
678 if (wire && !interfaceWires.contains(wire.get()))
679 internalWires.insert(wire.get());
680 }
681 }
682 for (const auto& bus : component->outputBuses()) {
683 for (const auto& wire : bus) {
684 if (wire && !interfaceWires.contains(wire.get()))
685 internalWires.insert(wire.get());
686 }
687 }
688 }
690 EXPECT_EQ(internalWires.size(), 2);
691}
692
693TEST_F(SubcircuitTest, ElaboratesNestedSubcircuitsIntoParentSimulation)
694{
695 project.upsertDocument(subcircuitDocument("and_gate", andSubcircuitDocument()));
696 project.upsertDocument(subcircuitDocument("nested_and", nestedAndSubcircuitDocument()));
697
698 auto component = std::make_shared<SubcircuitComponent>(&resolver);
699 component->setPropertyValue("slug", std::string("nested_and"));
700
701 auto inputA = std::make_shared<Wire>();
702 auto inputB = std::make_shared<Wire>();
703 auto output = std::make_shared<Wire>();
704 component->setInput(0, Bus{inputA});
705 component->setInput(1, Bus{inputB});
706 component->setOutput(0, Bus{output});
707
708 auto circuit = std::make_shared<Circuit>(component, false);
709 SILICON::simulation::Session simulator(circuit, {}, &resolver);
710
711 EXPECT_EQ(simulator.setBus(Bus{inputA}, valueFor(Bus{inputA}, 1)),
713 EXPECT_EQ(simulator.setBus(Bus{inputB}, valueFor(Bus{inputB}, 1)),
715 EXPECT_EQ(output->getCurrentState(), State::HIGH);
716}
717
718TEST_F(SubcircuitTest, DelayedGateInsideSubcircuitUsesParentEventQueue)
720 project.upsertDocument(
721 subcircuitDocument("delayed_not", delayedNotSubcircuitDocument()));
722
723 auto component = std::make_shared<SubcircuitComponent>(&resolver);
724 component->setPropertyValue("slug", std::string("delayed_not"));
725
726 auto input = std::make_shared<Wire>();
727 auto output = std::make_shared<Wire>();
728 component->setInput(0, Bus{input});
729 component->setOutput(0, Bus{output});
730
731 auto circuit = std::make_shared<Circuit>(component, false);
732 SILICON::simulation::Session simulator(circuit, {}, &resolver);
733
734 EXPECT_EQ(simulator.setBus(Bus{input}, valueFor(Bus{input}, 0)),
736 EXPECT_NE(output->getCurrentState(), State::HIGH);
737 EXPECT_EQ(simulator.run(1), Simulator::RunResult::Completed);
738 EXPECT_NE(output->getCurrentState(), State::HIGH);
739 EXPECT_EQ(simulator.run(1), Simulator::RunResult::Completed);
740 EXPECT_EQ(output->getCurrentState(), State::HIGH);
741 EXPECT_EQ(simulator.getCurrentTime(), 2);
742}
743
744TEST_F(SubcircuitTest, ReconcilesModuleConnectionsWithoutPersistentIdentities)
745{
746 project.upsertDocument(subcircuitDocument("and_gate", andSubcircuitDocument()));
747 auto component = std::make_shared<SubcircuitComponent>(&resolver);
748 component->setPropertyValue("slug", std::string("and_gate"));
749 const Bus connected(1);
750 component->setInputs({connected});
751 const auto definition = resolver.resolve("and_gate");
752 const auto inputs = component->inputsForPorts(definition.inputs);
753 ASSERT_EQ(inputs.size(), 2);
754 EXPECT_EQ(inputs[0], connected);
755 EXPECT_EQ(inputs[1].size(), 1);
756 EXPECT_NE(inputs[1][0], connected[0]);
757}
758
759TEST_F(SubcircuitTest, ReconcilesBusWidthsWithoutPersistentIdentities)
760{
761 project.upsertDocument(subcircuitDocument("bus_not", busNotCoreDocument()));
762 auto component = std::make_shared<SubcircuitComponent>(&resolver);
763 component->setPropertyValue("slug", std::string("bus_not"));
764 const Bus connected(4);
765 component->setInput(0, connected);
766 const auto definition = resolver.resolve("bus_not");
767 const auto inputs = component->inputsForPorts(definition.inputs);
768 ASSERT_EQ(inputs.size(), 1);
769 ASSERT_EQ(inputs[0].size(), definition.inputs[0].bus.size());
770 for (std::size_t bit = 0; bit < connected.size(); ++bit)
771 EXPECT_EQ(inputs[0][bit], connected[bit]);
772}
773
774TEST_F(SubcircuitTest, DirectSimulatorRejectsUnprocessedPlaceholder)
775{
776 project.upsertDocument(subcircuitDocument("and_gate", andSubcircuitDocument()));
777
778 auto component = std::make_shared<SubcircuitComponent>(&resolver);
779 component->setPropertyValue("slug", std::string("and_gate"));
780 auto source = std::make_shared<Circuit>(component, false);
781
782 try {
783 Simulator simulator(source);
784 FAIL() << "Expected direct placeholder simulation to fail";
785 } catch (const std::logic_error& error) {
786 EXPECT_NE(std::string(error.what()).find("preprocess the circuit"),
787 std::string::npos);
788 }
789}
790
791TEST_F(SubcircuitTest, ReplacementSessionResetsRuntimeAndSupportsTrace)
792{
793 auto input = std::make_shared<Wire>();
794 auto output = std::make_shared<Wire>();
795 auto gate = std::make_shared<NotGate>(input, output);
796 gate->setPropertyValue("delay", 5);
797
798 auto source = std::make_shared<Circuit>(gate, false);
799 auto session = std::make_unique<SILICON::simulation::Session>(
800 source, Simulator::CancellationCheck{}, &resolver);
801
802 std::vector<std::pair<std::uint64_t, std::vector<BusValue>>> snapshots;
803 const auto traceSink = [&snapshots](const std::uint64_t time,
804 const std::vector<BusValue>& values) {
805 snapshots.emplace_back(time, values);
806 };
807 session->setTraceBuses({{"output", Bus{output}}});
808 session->setTraceSink(traceSink);
809
810 EXPECT_EQ(session->setBus(Bus{input}, valueFor(Bus{input}, 0)),
812 EXPECT_EQ(session->run(2), Simulator::RunResult::Completed);
813 EXPECT_EQ(session->getCurrentTime(), 2);
814 EXPECT_NE(output->getCurrentState(), State::HIGH);
815
816 // The old runtime has a HIGH transition queued for t=5. Replace the source topology
817 // with an identity AND gate and create a fresh session without the pending event.
818 session.reset();
819 input->forceSetCurrentState(State::HIGH);
820 source->removeComponent(gate);
821 auto replacementGate =
822 std::make_shared<AndGate>(std::vector<Wire_ptr>{input, input}, output);
823 replacementGate->setPropertyValue("delay", 0);
824 source->addComponent(replacementGate);
825 session = std::make_unique<SILICON::simulation::Session>(
826 source, Simulator::CancellationCheck{}, &resolver);
827 session->setTraceBuses({{"output", Bus{output}}});
828 session->setTraceSink(traceSink);
829
830 EXPECT_EQ(session->getCurrentTime(), 0);
831 EXPECT_EQ(output->getCurrentState(), State::HIGH);
832 ASSERT_FALSE(snapshots.empty());
833 EXPECT_EQ(snapshots.back().first, 0);
834 ASSERT_EQ(snapshots.back().second.size(), 1);
835 EXPECT_EQ(snapshots.back().second[0], busValueFromBits("1"));
837 EXPECT_EQ(session->run(6), Simulator::RunResult::Completed);
838 EXPECT_EQ(output->getCurrentState(), State::HIGH);
839}
840
841TEST_F(SubcircuitTest, FailedReplacementSessionKeepsPreviousRuntimeUsable)
842{
843 project.upsertDocument(subcircuitDocument("and_gate", andSubcircuitDocument()));
844
845 auto component = std::make_shared<SubcircuitComponent>(&resolver);
846 component->setPropertyValue("slug", std::string("and_gate"));
847 auto source = std::make_shared<Circuit>(component, false);
848 SILICON::simulation::Session session(source, {}, &resolver);
849
850 EXPECT_EQ(session.run(1), Simulator::RunResult::Completed);
851 // A replacement without the required project resolver must not disturb the runtime.
852 EXPECT_THROW(SILICON::simulation::Session replacement(source), std::runtime_error);
853
854 EXPECT_EQ(session.getCurrentTime(), 1);
855 EXPECT_EQ(session.run(1), Simulator::RunResult::Completed);
856 EXPECT_EQ(session.getCurrentTime(), 2);
857}
858
859TEST_F(SubcircuitTest, RejectsRecursiveSubcircuitDependenciesDuringElaboration)
860{
861 RecursiveCircuitResolver recursiveResolver;
862 auto component = SubcircuitComponent::imported("a", {}, {}, {}, {});
863 Circuit source(component, false);
864 SILICON::simulation::CircuitElaborator elaborator(registry, &recursiveResolver);
865
866 try {
867 static_cast<void>(elaborator.elaborate(source));
868 FAIL() << "Expected recursive subcircuits to fail";
869 } catch (const std::runtime_error& error) {
870 EXPECT_NE(std::string(error.what())
871 .find("Recursive subcircuit dependency detected: a -> b -> a"),
872 std::string::npos);
873 }
874}
875
876TEST_F(SubcircuitTest, ParsesCircuitDocumentWithoutGuiObjects)
877{
880 .circuit;
881
882 ASSERT_EQ(circuit.getInputs().size(), 2);
883 ASSERT_EQ(circuit.getOutputs().size(), 1);
884 EXPECT_EQ(circuit.getInputs()[0].size(), 1);
885 EXPECT_EQ(circuit.getInputs()[1].size(), 1);
886 EXPECT_EQ(circuit.getOutputs()[0].size(), 1);
887 ASSERT_NE(circuit.getComponentByVertexId(0), nullptr);
888 EXPECT_EQ(circuit.getComponentByVertexId(0)->typeName(), AndGate::Type);
889}
890
891TEST_F(SubcircuitTest, ResolvesGraphicalSubcircuitFromPersistedContents)
892{
893 project.upsertDocument(
894 subcircuitDocument("graphical_bus", graphicalBusSubcircuitDocument()));
895
896 const auto definition = resolver.resolve("graphical_bus");
897 ASSERT_EQ(definition.inputs.size(), 1);
898 ASSERT_EQ(definition.outputs.size(), 1);
899 EXPECT_EQ(definition.inputs[0].name, "data");
900 EXPECT_EQ(definition.outputs[0].name, "result");
901
902 auto component = std::make_shared<SubcircuitComponent>(&resolver);
903 component->setPropertyValue("slug", std::string("graphical_bus"));
905 ASSERT_EQ(component->getInputs().size(), 1);
906 ASSERT_EQ(component->getOutputs().size(), 1);
907 EXPECT_EQ(component->getInputs()[0].size(), 8);
908 EXPECT_EQ(component->getOutputs()[0].size(), 8);
909}
910
911TEST_F(SubcircuitTest, ResolvesCircuitReadDirectlyFromProjectArchive)
912{
913 const auto path = temporaryProjectPath();
914 ProjectFileCleanup cleanup{path};
915 const auto timestamp = currentUtcTimestamp();
917 path, {.metadata = {.formatVersion = FORMAT_VERSION,
918 .siliconVersion = SILICON_VERSION,
919 .creationDate = timestamp,
920 .lastModify = timestamp},
921 .project = {.name = "resolver test", .description = ""},
922 .documents = {
923 {std::string(DEFAULT_CIRCUIT_PATH), graphicalAndSubcircuitDocument()},
924 subcircuitDocument("persisted", graphicalBusSubcircuitDocument())}});
925
926 ProjectContext loadedProject;
927 loadedProject.setDocuments(readProjectFile(path).documents);
928 ProjectCircuitResolver loadedResolver{loadedProject, registry};
929
930 const auto definition = loadedResolver.resolve("persisted");
931 ASSERT_EQ(definition.inputs.size(), 1);
932 ASSERT_EQ(definition.outputs.size(), 1);
933 EXPECT_EQ(definition.inputs[0].name, "data");
934 EXPECT_EQ(definition.outputs[0].name, "result");
936
937TEST_F(SubcircuitTest, HydratesRomSnapshotsInNestedResolvedDefinitions)
938{
939 project.upsertDocument({documentPathForSlug(DocumentType::RawBinary, "program"),
940 std::string("\x10\x20\x30\x40", 4)});
941 project.upsertDocument(subcircuitDocument("rom_leaf", romSubcircuitDocument()));
942 project.upsertDocument(subcircuitDocument("rom_parent", nestedRomSubcircuitDocument()));
943
944 auto root = std::make_shared<SubcircuitComponent>(&resolver);
945 root->setPropertyValue("slug", std::string("rom_parent"));
946 Circuit source(root, false);
947
948 CircuitElaborator elaborator(registry, &resolver);
949 auto runtime = elaborator.elaborate(source);
950
951 ASSERT_EQ(runtime->getComponentToVertex().size(), 1);
952 const auto rom = std::dynamic_pointer_cast<ROM>(runtime->getComponentByVertexId(0));
953 ASSERT_NE(rom, nullptr);
954 ASSERT_NE(rom->binaryContentsSnapshot(), nullptr);
955 EXPECT_EQ(*rom->binaryContentsSnapshot(), std::string("\x10\x20\x30\x40", 4));
956 EXPECT_EQ(rom->inputBuses()[0].size(), 2);
957}
958
959TEST_F(SubcircuitTest, SimulatesRomInsideSingleSubcircuit)
960{
961 project.upsertDocument({documentPathForSlug(DocumentType::RawBinary, "program"),
962 std::string("\x10\x20\x30\x40", 4)});
963 project.upsertDocument(subcircuitDocument("rom_sim_leaf", romSimulationLeafDocument()));
964
965 auto component = std::make_shared<SubcircuitComponent>(&resolver);
966 component->setPropertyValue("slug", std::string("rom_sim_leaf"));
967
968 Bus address(2);
969 auto cs = std::make_shared<Wire>();
970 auto oe = std::make_shared<Wire>();
971 Bus data(8);
972 component->setInput(0, address);
973 component->setInput(1, Bus{cs});
974 component->setInput(2, Bus{oe});
975 component->setOutput(0, data);
976
977 auto circuit = std::make_shared<Circuit>(component, false);
978 SILICON::simulation::Session simulator(circuit, {}, &resolver);
979
980 ASSERT_EQ(simulator.setBus(Bus{cs}, valueFor(Bus{cs}, 1)),
982 const std::array<std::uint8_t, 4> expected{0x10, 0x20, 0x30, 0x40};
983 for (std::size_t index = 0; index < expected.size(); ++index) {
984 ASSERT_EQ(simulator.setBus(address, valueFor(address, index)),
986 EXPECT_EQ(data.getCurrentValue(), valueFor(data, expected[index])) << index;
987 }
988}
989
990TEST_F(SubcircuitTest, SimulatesRomInsideNestedSubcircuits)
991{
992 project.upsertDocument({documentPathForSlug(DocumentType::RawBinary, "program"),
993 std::string("\x10\x20\x30\x40", 4)});
994 project.upsertDocument(subcircuitDocument("rom_sim_leaf", romSimulationLeafDocument()));
995 project.upsertDocument(
996 subcircuitDocument("rom_sim_parent", romSimulationParentDocument()));
997
998 auto component = std::make_shared<SubcircuitComponent>(&resolver);
999 component->setPropertyValue("slug", std::string("rom_sim_parent"));
1000
1001 Bus address(2);
1002 auto cs = std::make_shared<Wire>();
1003 auto oe = std::make_shared<Wire>();
1004 Bus data(8);
1005 component->setInput(0, address);
1006 component->setInput(1, Bus{cs});
1007 component->setInput(2, Bus{oe});
1008 component->setOutput(0, data);
1009
1010 auto circuit = std::make_shared<Circuit>(component, false);
1011 SILICON::simulation::Session simulator(circuit, {}, &resolver);
1012
1013 ASSERT_EQ(simulator.setBus(Bus{cs}, valueFor(Bus{cs}, 1)),
1015 const std::array<std::uint8_t, 4> expected{0x10, 0x20, 0x30, 0x40};
1016 for (std::size_t index = 0; index < expected.size(); ++index) {
1017 ASSERT_EQ(simulator.setBus(address, valueFor(address, index)),
1019 EXPECT_EQ(data.getCurrentValue(), valueFor(data, expected[index])) << index;
1020 }
1021}
1022
1023TEST_F(SubcircuitTest, ElaboratedRomRuntimeStaysStableAfterSourceRefresh)
1025 project.upsertDocument({documentPathForSlug(DocumentType::RawBinary, "program"),
1026 std::string("\x10\x20\x30\x40", 4)});
1027 project.upsertDocument(subcircuitDocument("rom_sim_leaf", romSimulationLeafDocument()));
1028
1029 auto component = std::make_shared<SubcircuitComponent>(&resolver);
1030 component->setPropertyValue("slug", std::string("rom_sim_leaf"));
1031
1032 Bus address(2);
1033 auto cs = std::make_shared<Wire>();
1034 auto oe = std::make_shared<Wire>();
1035 Bus data(8);
1036 component->setInput(0, address);
1037 component->setInput(1, Bus{cs});
1038 component->setInput(2, Bus{oe});
1039 component->setOutput(0, data);
1040
1041 auto circuit = std::make_shared<Circuit>(component, false);
1042 SILICON::simulation::Session simulator(circuit, {}, &resolver);
1043
1044 ASSERT_EQ(simulator.setBus(Bus{cs}, valueFor(Bus{cs}, 1)),
1046 ASSERT_EQ(simulator.setBus(address, valueFor(address, 1)),
1048 EXPECT_EQ(data.getCurrentValue(), valueFor(data, 0x20));
1049
1050 // Replacing the project binary document and re-resolving the definition must not
1051 // disturb the already elaborated runtime clone.
1052 project.upsertDocument({documentPathForSlug(DocumentType::RawBinary, "program"),
1053 std::string("\xDE\xAD\xBE\xEF", 4)});
1054 static_cast<void>(resolver.resolve("rom_sim_leaf"));
1055
1056 ASSERT_EQ(simulator.setBus(address, valueFor(address, 1)),
1058 EXPECT_EQ(data.getCurrentValue(), valueFor(data, 0x20));
1059}
1060
1061TEST_F(SubcircuitTest, ProjectResolversWithSameSlugRemainIndependent)
1062{
1063 ProjectContext firstProject;
1064 ProjectContext secondProject;
1065 firstProject.setDocuments(
1066 {subcircuitDocument("shared", graphicalAndSubcircuitDocument())});
1067 secondProject.setDocuments(
1068 {subcircuitDocument("shared", graphicalBusSubcircuitDocument())});
1069 ProjectCircuitResolver firstResolver{firstProject, registry};
1070 ProjectCircuitResolver secondResolver{secondProject, registry};
1071
1072 const auto first = firstResolver.resolve("shared");
1073 const auto second = secondResolver.resolve("shared");
1074 EXPECT_EQ(first.inputs.size(), 2);
1075 ASSERT_EQ(second.inputs.size(), 1);
1076 EXPECT_EQ(second.inputs[0].bus.size(), 8);
1077}
1078
1079TEST_F(SubcircuitTest, ElaboratesMultipleGraphicalSubcircuits)
1080{
1081 project.upsertDocument(
1082 subcircuitDocument("graphical_and", graphicalAndSubcircuitDocument()));
1083 project.upsertDocument(
1084 subcircuitDocument("graphical_not", delayedNotSubcircuitDocument()));
1085
1086 auto graphical = std::make_shared<SubcircuitComponent>(&resolver);
1087 auto inverter = std::make_shared<SubcircuitComponent>(&resolver);
1088 graphical->setPropertyValue("slug", std::string("graphical_and"));
1089 inverter->setPropertyValue("slug", std::string("graphical_not"));
1091 auto graphicalInputA = std::make_shared<Wire>();
1092 auto graphicalInputB = std::make_shared<Wire>();
1093 auto graphicalOutput = std::make_shared<Wire>();
1094 auto inverterInput = std::make_shared<Wire>();
1095 auto inverterOutput = std::make_shared<Wire>();
1096 graphical->setInput(0, Bus{graphicalInputA});
1097 graphical->setInput(1, Bus{graphicalInputB});
1098 graphical->setOutput(0, Bus{graphicalOutput});
1099 inverter->setInput(0, Bus{inverterInput});
1100 inverter->setOutput(0, Bus{inverterOutput});
1101
1102 auto source = std::make_shared<Circuit>(Component_set{graphical, inverter}, false);
1104 &resolver);
1105 auto runtime = elaborator.elaborate(*source);
1106
1107 std::size_t andCount = 0;
1108 std::size_t notCount = 0;
1109 for (const auto& [component, _vertex] : runtime->getComponentToVertex()) {
1110 EXPECT_NE(component->typeName(), SubcircuitComponent::Type);
1111 andCount += component->typeName() == AndGate::Type;
1112 notCount += component->typeName() == NotGate::Type;
1113 }
1114 EXPECT_EQ(andCount, 1);
1115 EXPECT_EQ(notCount, 1);
1116
1117 SILICON::simulation::Session session(source, {}, &resolver);
1118 EXPECT_EQ(session.setBus(Bus{graphicalInputA}, valueFor(Bus{graphicalInputA}, 1)),
1120 EXPECT_EQ(session.setBus(Bus{graphicalInputB}, valueFor(Bus{graphicalInputB}, 1)),
1122 EXPECT_EQ(session.setBus(Bus{inverterInput}, valueFor(Bus{inverterInput}, 0)),
1124 EXPECT_EQ(session.runUntilIdle(), Simulator::RunResult::Completed);
1125 EXPECT_EQ(graphicalOutput->getCurrentState(), State::HIGH);
1126 EXPECT_EQ(inverterOutput->getCurrentState(), State::HIGH);
1127}
1128
1129TEST_F(SubcircuitTest, CircuitUsesPortRoleDeclaredInterface)
1130{
1131 const auto definition = SILICON::core::parseCircuitDocument(
1132 graphicalAndSubcircuitDocument(), ComponentRegistry::instance(), &resolver);
1133 const auto& inputs = definition.inputs;
1134 const auto& outputs = definition.outputs;
1135 ASSERT_EQ(inputs.size(), 2);
1136 ASSERT_EQ(outputs.size(), 1);
1137 EXPECT_EQ(inputs[0].name, "a");
1138 EXPECT_EQ(inputs[1].name, "b");
1139 EXPECT_EQ(outputs[0].name, "q");
1140 EXPECT_EQ(inputs[0].boundaryVertex, 0);
1141 EXPECT_EQ(inputs[1].boundaryVertex, 1);
1142 EXPECT_EQ(outputs[0].boundaryVertex, 3);
1143}
1144
1145TEST_F(SubcircuitTest, CircuitUsesDeterministicTopologyFallbackPortNames)
1146{
1147 const auto definition = SILICON::core::parseCircuitDocument(
1149 const auto& inputs = definition.inputs;
1150 const auto& outputs = definition.outputs;
1151 ASSERT_EQ(inputs.size(), 2);
1152 ASSERT_EQ(outputs.size(), 1);
1153 EXPECT_EQ(inputs[0].name, "input_0");
1154 EXPECT_EQ(inputs[1].name, "input_1");
1155 EXPECT_EQ(outputs[0].name, "output_0");
1156}
1157
1158TEST_F(SubcircuitTest, CircuitPreservesDuplicateAndEmptyBoundaryNames)
1159{
1160 auto document = nlohmann::json::parse(graphicalAndSubcircuitDocument());
1161 document["circuit"]["components"][0]["properties"]["name"] = "data";
1162 document["circuit"]["components"][1]["properties"]["name"] = "data";
1163 document["circuit"]["components"][3]["properties"]["name"] = "";
1164 const auto circuit =
1165 Circuit::deserialize(document["circuit"].dump(), ComponentRegistry::instance());
1167 const auto inputs = circuit.getInputPorts();
1168 const auto outputs = circuit.getOutputPorts();
1169 ASSERT_EQ(inputs.size(), 2);
1170 ASSERT_EQ(outputs.size(), 1);
1171 EXPECT_EQ(inputs[0].name, "data");
1172 EXPECT_EQ(inputs[1].name, "data");
1173 EXPECT_TRUE(outputs[0].name.empty());
1174}
1175
1176TEST_F(SubcircuitTest, UsesBoundaryComponentsForFeedbackOutputs)
1177{
1178 project.upsertDocument(
1179 subcircuitDocument("feedback_latch", feedbackLatchCoreDocument()));
1180
1181 auto component = std::make_shared<SubcircuitComponent>(&resolver);
1182 component->setPropertyValue("slug", std::string("feedback_latch"));
1183
1184 EXPECT_EQ(component->getInputs().size(), 2);
1185 ASSERT_EQ(component->getOutputs().size(), 2);
1186 EXPECT_EQ(component->getOutputs()[0].size(), 1);
1187 EXPECT_EQ(component->getOutputs()[1].size(), 1);
1188}
1189
1190TEST_F(SubcircuitTest, SimulatesFeedbackSubcircuitWithBoundaryOutputs)
1192 project.upsertDocument(
1193 subcircuitDocument("feedback_latch", feedbackLatchCoreDocument()));
1194
1195 auto component = std::make_shared<SubcircuitComponent>(&resolver);
1196 component->setPropertyValue("slug", std::string("feedback_latch"));
1197
1198 auto set = std::make_shared<Wire>(State::LOW);
1199 auto reset = std::make_shared<Wire>(State::HIGH);
1200 auto q = std::make_shared<Wire>(State::UNKNOWN);
1201 auto notQ = std::make_shared<Wire>(State::UNKNOWN);
1202 component->setInput(0, Bus{set});
1203 component->setInput(1, Bus{reset});
1204 component->setOutput(0, Bus{q});
1205 component->setOutput(1, Bus{notQ});
1206
1207 auto circuit = std::make_shared<Circuit>(component, false);
1208 SILICON::simulation::Session simulator(circuit, {}, &resolver);
1209
1210 EXPECT_EQ(q->getCurrentState(), State::HIGH);
1211 EXPECT_EQ(notQ->getCurrentState(), State::LOW);
1212
1213 EXPECT_EQ(simulator.setBus(Bus{reset}, valueFor(Bus{reset}, 0)),
1215 EXPECT_EQ(simulator.setBus(Bus{set}, valueFor(Bus{set}, 1)),
1217 EXPECT_EQ(q->getCurrentState(), State::LOW);
1218 EXPECT_EQ(notQ->getCurrentState(), State::HIGH);
1219}
1220
1221TEST_F(SubcircuitTest, SimulatesGraphicalSubcircuitDocument)
1222{
1223 project.upsertDocument(
1224 subcircuitDocument("graphical_and", graphicalAndSubcircuitDocument()));
1225
1226 auto component = std::make_shared<SubcircuitComponent>(&resolver);
1227 component->setPropertyValue("slug", std::string("graphical_and"));
1228
1229 auto inputA = std::make_shared<Wire>();
1230 auto inputB = std::make_shared<Wire>();
1231 auto output = std::make_shared<Wire>();
1232 component->setInput(0, Bus{inputA});
1233 component->setInput(1, Bus{inputB});
1234 component->setOutput(0, Bus{output});
1235
1236 auto circuit = std::make_shared<Circuit>(component, false);
1237 SILICON::simulation::Session simulator(circuit, {}, &resolver);
1238
1239 EXPECT_EQ(simulator.setBus(Bus{inputA}, valueFor(Bus{inputA}, 1)),
1241 EXPECT_EQ(simulator.setBus(Bus{inputB}, valueFor(Bus{inputB}, 1)),
1243 EXPECT_EQ(output->getCurrentState(), State::HIGH);
1244}
1245
1246TEST_F(SubcircuitTest, RejectsUnknownSlug)
1247{
1248 auto component = std::make_shared<SubcircuitComponent>(&resolver);
1249 try {
1250 component->setPropertyValue("slug", std::string("missing"));
1251 FAIL() << "Expected an unknown slug to fail";
1252 } catch (const std::runtime_error& error) {
1253 EXPECT_NE(std::string(error.what()).find("Unknown subcircuit slug 'missing'"),
1254 std::string::npos);
1255 }
1256}
1257
1258TEST_F(SubcircuitTest, DocumentStoreNotifiesSpecificAndGlobalChanges)
1259{
1260 const auto& store = project.documents();
1261 std::vector<SILICON::project::DocumentChange> notifications;
1262 const auto listenerId =
1263 store.addListener([&notifications](const SILICON::project::DocumentChange& change) {
1264 notifications.push_back(change);
1265 });
1267 project.upsertDocument(subcircuitDocument("adder", andSubcircuitDocument()));
1268 project.removeDocument("circuits/adder.json");
1269 project.setDocuments({});
1270 store.removeListener(listenerId);
1271
1272 ASSERT_EQ(notifications.size(), 3);
1273 EXPECT_EQ(notifications[0].kind, SILICON::project::DocumentChangeKind::Added);
1274 EXPECT_EQ(notifications[0].path, "circuits/adder.json");
1275 EXPECT_EQ(notifications[1].kind, SILICON::project::DocumentChangeKind::Removed);
1276 EXPECT_EQ(notifications[1].path, "circuits/adder.json");
1277 EXPECT_EQ(notifications[2].kind, SILICON::project::DocumentChangeKind::Reset);
1278 EXPECT_FALSE(notifications[2].path);
1279}
1280
1281namespace {
1282
1283nlohmann::json identityTestDocument()
1284{
1285 auto document = nlohmann::json::parse(graphicalAndSubcircuitDocument())["circuit"];
1286 auto& components = document["components"];
1287 components[2]["type"] = "NotGate";
1288 components[2]["inputs"] = {{1}};
1289 components.push_back({{"id", 4},
1290 {"type", "DummyOutputComponent"},
1291 {"properties", {{"name", "pass_b"}}},
1292 {"inputs", {{5}}},
1293 {"outputs", nlohmann::json::array()}});
1294 // Use real drivers on both outputs so neither boundary aliases an input wire.
1295 for (int id = 5; id <= 6; ++id)
1296 components.push_back({{"id", id},
1297 {"type", "NotGate"},
1298 {"properties", {{"delay", 0}, {"size", 1}}},
1299 {"inputs", {{id == 5 ? 2 : 4}}},
1300 {"outputs", {{id == 5 ? 4 : 5}}}});
1301 return document;
1302}
1303
1304nlohmann::json reorderedIdentityDocument(nlohmann::json document)
1305{
1306 for (auto& component : document["components"]) {
1307 const auto id = component["id"].get<int>();
1308 if (id == 0 || id == 1)
1309 component["id"] = 1 - id;
1310 if (id == 3 || id == 4)
1311 component["id"] = 7 - id;
1312 // Names, including duplicate names, must not act as identities.
1313 if (component["properties"].contains("name"))
1314 component["properties"]["name"] = "renamed";
1315 }
1316 return document;
1317}
1318
1319} // namespace
1320
1321TEST_F(SubcircuitTest, ReloadPreservesConnectionsWhenPortsReorderAndRename)
1322{
1323 const auto definition = Circuit::deserialize(identityTestDocument().dump(), registry);
1324 const auto savedDefinition = nlohmann::json::parse(definition.serialize());
1325 project.upsertDocument(subcircuitDocument("identity", savedDefinition.dump()));
1326 auto instance = std::make_shared<SubcircuitComponent>(&resolver);
1327 instance->setPropertyValue("slug", std::string("identity"));
1328 const auto a = instance->getInputs()[0];
1329 const auto b = instance->getInputs()[1];
1330 const auto invertedA = instance->getOutputs()[0];
1331 const auto passB = instance->getOutputs()[1];
1332 const auto inputIds = instance->inputPortIds();
1333 const auto outputIds = instance->outputPortIds();
1334
1335 project.upsertDocument(
1336 subcircuitDocument("identity", reorderedIdentityDocument(savedDefinition).dump()));
1337 instance->reloadFromResolver();
1338 EXPECT_EQ(instance->getInputs()[0], b);
1339 EXPECT_EQ(instance->getInputs()[1], a);
1340 EXPECT_EQ(instance->getOutputs()[0], passB);
1341 EXPECT_EQ(instance->getOutputs()[1], invertedA);
1342 EXPECT_EQ(instance->inputPortIds()[1], inputIds[0]);
1343 EXPECT_EQ(instance->outputPortIds()[1], outputIds[0]);
1344
1345 auto circuit = std::make_shared<Circuit>(instance, false);
1346 Session simulator(circuit, {}, &resolver);
1347 ASSERT_EQ(simulator.setBus(a, valueFor(a, 1)), Simulator::RunResult::Completed);
1348 ASSERT_EQ(simulator.setBus(b, valueFor(b, 1)), Simulator::RunResult::Completed);
1349 EXPECT_EQ(invertedA.getCurrentValue(), valueFor(invertedA, 0));
1350 EXPECT_EQ(passB.getCurrentValue(), valueFor(passB, 1));
1351}
1352
1353TEST_F(SubcircuitTest, SavedAndUnrefreshedInstancesRemapToChangedDefinition)
1354{
1355 const auto definition = Circuit::deserialize(identityTestDocument().dump(), registry);
1356 const auto savedDefinition = nlohmann::json::parse(definition.serialize());
1357 project.upsertDocument(subcircuitDocument("identity", savedDefinition.dump()));
1358 auto instance = std::make_shared<SubcircuitComponent>(&resolver);
1359 instance->setPropertyValue("slug", std::string("identity"));
1360 auto circuit = std::make_shared<Circuit>(instance, false);
1361 const auto savedInstance = circuit->serialize();
1362 const auto a = instance->getInputs()[0];
1363 const auto b = instance->getInputs()[1];
1364 const auto invertedA = instance->getOutputs()[0];
1365 const auto passB = instance->getOutputs()[1];
1366
1367 project.upsertDocument(
1368 subcircuitDocument("identity", reorderedIdentityDocument(savedDefinition).dump()));
1369 // Headless callers do not receive GUI document-change notifications.
1370 Session simulator(circuit, {}, &resolver);
1371 ASSERT_EQ(simulator.setBus(a, valueFor(a, 1)), Simulator::RunResult::Completed);
1372 ASSERT_EQ(simulator.setBus(b, valueFor(b, 1)), Simulator::RunResult::Completed);
1373 EXPECT_EQ(invertedA.getCurrentValue(), valueFor(invertedA, 0));
1374 EXPECT_EQ(passB.getCurrentValue(), valueFor(passB, 1));
1375
1376 auto restored = Circuit::deserialize(savedInstance, registry, &resolver);
1377 const auto restoredInstance = restored.getComponentByVertexId(0);
1378 EXPECT_EQ(restoredInstance->getInputs()[1][0]->getId(), a[0]->getId());
1379 EXPECT_EQ(restoredInstance->getInputs()[0][0]->getId(), b[0]->getId());
1380 EXPECT_EQ(restoredInstance->getOutputs()[1][0]->getId(), invertedA[0]->getId());
1381 EXPECT_EQ(restoredInstance->getOutputs()[0][0]->getId(), passB[0]->getId());
1382 const auto savedAgain = nlohmann::json::parse(restored.serialize())["components"][0];
1383 EXPECT_EQ(savedAgain["inputPortIds"][0], instance->inputPortIds()[1]);
1384 EXPECT_EQ(savedAgain["outputPortIds"][0], instance->outputPortIds()[1]);
1385}
1386
1387TEST_F(SubcircuitTest, ReloadKeepsResizedPortAndDoesNotReuseRemovedConnection)
1388{
1389 auto document = nlohmann::json::parse(graphicalBusSubcircuitDocument())["circuit"];
1390 auto definition = Circuit::deserialize(document.dump(), registry);
1391 document = nlohmann::json::parse(definition.serialize());
1392 project.upsertDocument(subcircuitDocument("identity", document.dump()));
1393 auto instance = std::make_shared<SubcircuitComponent>(&resolver);
1394 instance->setPropertyValue("slug", std::string("identity"));
1395 const auto original = instance->getInputs()[0];
1396
1397 document["components"][0]["properties"]["size"] = 16;
1398 for (int wire = 20; wire < 28; ++wire)
1399 document["components"][0]["outputs"][0].push_back(wire);
1400 project.upsertDocument(subcircuitDocument("identity", document.dump()));
1401 instance->reloadFromResolver();
1402 ASSERT_EQ(instance->getInputs()[0].size(), 16);
1403 for (std::size_t bit = 0; bit < original.size(); ++bit)
1404 EXPECT_EQ(instance->getInputs()[0][bit], original[bit]);
1405
1406 document["components"][0]["portId"] = 1000000;
1407 project.upsertDocument(subcircuitDocument("identity", document.dump()));
1408 instance->reloadFromResolver();
1409 EXPECT_NE(instance->getInputs()[0][0], original[0]);
1410}
1411
1412TEST_F(SubcircuitTest, RejectsAmbiguousSavedPortIdentities)
1413{
1414 project.upsertDocument(subcircuitDocument("identity", identityTestDocument().dump()));
1415 auto instance = std::make_shared<SubcircuitComponent>(&resolver);
1416 instance->setPropertyValue("slug", std::string("identity"));
1417 Circuit circuit(instance, false);
1418 auto document = nlohmann::json::parse(circuit.serialize());
1419 document["components"][0]["inputPortIds"] = {1, 1};
1420 EXPECT_THROW(
1421 static_cast<void>(Circuit::deserialize(document.dump(), registry, &resolver)),
1422 std::runtime_error);
1423}
1424
1425TEST_F(SubcircuitTest, YosysExportPreservesConnectionsAfterDefinitionReorder)
1426{
1427 auto definition = Circuit::deserialize(identityTestDocument().dump(), registry);
1428 auto savedDefinition = nlohmann::json::parse(definition.serialize());
1429 project.upsertDocument(subcircuitDocument("identity", savedDefinition.dump()));
1430 auto instance = std::make_shared<SubcircuitComponent>(&resolver);
1431 instance->setPropertyValue("slug", std::string("identity"));
1432 auto a = std::make_shared<DummyInputComponent>(instance->getInputs()[0], "a");
1433 auto b = std::make_shared<DummyInputComponent>(instance->getInputs()[1], "b");
1434 auto y = std::make_shared<DummyOutputComponent>(instance->getOutputs()[0], "y");
1435 auto z = std::make_shared<DummyOutputComponent>(instance->getOutputs()[1], "z");
1436 Circuit root(std::vector<Component_ptr>{a, b, instance, y, z}, false);
1437 const auto before = nlohmann::json::parse(SILICON::yosys::serialize(root, "top"));
1438 for (auto& component : savedDefinition["components"]) {
1439 const auto id = component["id"].get<int>();
1440 if (id == 0 || id == 1)
1441 component["id"] = 1 - id;
1442 if (id == 3 || id == 4)
1443 component["id"] = 7 - id;
1444 }
1445 project.upsertDocument(subcircuitDocument("identity", savedDefinition.dump()));
1446 const auto after = nlohmann::json::parse(SILICON::yosys::serialize(root, "top"));
1447 for (const auto* design : {&before, &after}) {
1448 const auto& top = (*design)["modules"]["top"];
1449 const auto& connections = top["cells"].begin().value()["connections"];
1450 EXPECT_EQ(connections["a"], top["ports"]["a"]["bits"]);
1451 EXPECT_EQ(connections["b"], top["ports"]["b"]["bits"]);
1452 EXPECT_EQ(connections["q"], top["ports"]["y"]["bits"]);
1453 EXPECT_EQ(connections["pass_b"], top["ports"]["z"]["bits"]);
1454 }
1455}
1456
1457TEST_F(SubcircuitTest, UnrefreshedInstancesReconcileWidthsWithUnchangedIds)
1458{
1459 auto document = nlohmann::json::parse(graphicalBusSubcircuitDocument())["circuit"];
1460 auto definition = Circuit::deserialize(document.dump(), registry);
1461 document = nlohmann::json::parse(definition.serialize());
1462 project.upsertDocument(subcircuitDocument("identity", document.dump()));
1463 auto instance = std::make_shared<SubcircuitComponent>(&resolver);
1464 instance->setPropertyValue("slug", std::string("identity"));
1465 const auto originalInput = instance->getInputs()[0];
1466 const auto originalOutput = instance->getOutputs()[0];
1467 const auto inputIds = instance->inputPortIds();
1468 const auto outputIds = instance->outputPortIds();
1469
1470 for (auto& component : document["components"]) {
1471 component["properties"]["size"] = 16;
1472 for (const auto* direction : {"inputs", "outputs"}) {
1473 for (auto& bus : component[direction]) {
1474 const int start = bus[0] == 1 ? 17 : 25;
1475 for (int i = 0; i < 8; ++i)
1476 bus.push_back(start + i);
1477 }
1478 }
1479 }
1480 project.upsertDocument(subcircuitDocument("identity", document.dump()));
1481 const auto updated = resolver.resolve("identity");
1482 const auto inputs = instance->inputsForPorts(updated.inputs);
1483 const auto outputs = instance->outputsForPorts(updated.outputs);
1484 EXPECT_EQ(instance->inputPortIds(), inputIds);
1485 EXPECT_EQ(instance->outputPortIds(), outputIds);
1486 ASSERT_EQ(inputs[0].size(), 16);
1487 ASSERT_EQ(outputs[0].size(), 16);
1488 for (std::size_t bit = 0; bit < 8; ++bit) {
1489 EXPECT_EQ(inputs[0][bit], originalInput[bit]);
1490 EXPECT_EQ(outputs[0][bit], originalOutput[bit]);
1491 }
1492 Circuit root(instance, false);
1493 const auto exported = nlohmann::json::parse(SILICON::yosys::serialize(root, "top"));
1494 const auto& connections =
1495 exported["modules"]["top"]["cells"].begin().value()["connections"];
1496 EXPECT_EQ(connections["data"].size(), 16);
1497 EXPECT_EQ(connections["result"].size(), 16);
1498
1499 for (auto& component : document["components"]) {
1500 component["properties"]["size"] = 4;
1501 for (const auto* direction : {"inputs", "outputs"})
1502 for (auto& bus : component[direction])
1503 bus.erase(bus.begin() + 4, bus.end());
1504 }
1505 project.upsertDocument(subcircuitDocument("identity", document.dump()));
1506 const auto reduced = resolver.resolve("identity");
1507 const auto reducedInputs = instance->inputsForPorts(reduced.inputs);
1508 const auto reducedOutputs = instance->outputsForPorts(reduced.outputs);
1509 ASSERT_EQ(reducedInputs[0].size(), 4);
1510 ASSERT_EQ(reducedOutputs[0].size(), 4);
1511 for (std::size_t bit = 0; bit < 4; ++bit) {
1512 EXPECT_EQ(reducedInputs[0][bit], originalInput[bit]);
1513 EXPECT_EQ(reducedOutputs[0][bit], originalOutput[bit]);
1514 }
1515}
1516
1517TEST_F(SubcircuitTest, RemovingBoundariesDoesNotRetargetNamedConnections)
1518{
1519 project.upsertDocument(
1520 subcircuitDocument("identity", graphicalAndSubcircuitDocument()));
1521 auto instance = std::make_shared<SubcircuitComponent>(&resolver);
1522 instance->setPropertyValue("slug", std::string("identity"));
1523 const auto oldInputs = instance->getInputs();
1524 const auto oldOutput = instance->getOutputs()[0];
1525 project.upsertDocument(subcircuitDocument("identity", andSubcircuitDocument()));
1526 const auto definition = resolver.resolve("identity");
1527 const auto inputs = instance->inputsForPorts(definition.inputs);
1528 const auto outputs = instance->outputsForPorts(definition.outputs);
1529 ASSERT_EQ(inputs.size(), 2);
1530 for (const auto& input : inputs)
1531 for (const auto& previous : oldInputs)
1532 EXPECT_NE(input[0], previous[0]);
1533 ASSERT_EQ(outputs.size(), 1);
1534 EXPECT_NE(outputs[0][0], oldOutput[0]);
1535}
static constexpr std::string_view Type
Definition gates.hpp:82
BusValue getCurrentValue() const
Definition wire.cpp:530
Represents a digital circuit as a directed graph of components.
Definition circuit.hpp:125
static Circuit deserialize(const std::string &jsonStr, const ComponentRegistry &reg, const CircuitResolver *resolver=nullptr)
Deserializes the core circuit model from a JSON string.
Definition circuit.cpp:749
static ComponentRegistry empty()
static ComponentRegistry & instance()
static constexpr std::string_view Type
Definition gates.hpp:117
static constexpr std::string_view Type
static std::shared_ptr< SubcircuitComponent > imported(std::string slug, std::vector< std::string > inputNames, std::vector< Bus > inputs, std::vector< std::string > outputNames, std::vector< Bus > outputs)
Creates an imported module instance before its project document exists.
SILICON::core::SubcircuitDefinition resolve(std::string_view slug) const override
void setDocuments(std::vector< Document > documents)
Converts source designs into simulator-ready runtime circuits.
Elaborates a source design once and owns its runtime Simulator.
Executes event-driven simulation of a Circuit.
Definition simulator.hpp:74
std::function< bool()> CancellationCheck
Framework-independent cooperative cancellation callback.
Definition simulator.hpp:89
std::optional< Gate > gate(Cell *cell, SigMap &signals)
RTLIL::IdString id(const char *name)
SubcircuitDefinition parseCircuitDocument(const std::string_view contents, const ComponentRegistry &registry, const CircuitResolver *resolver)
void registerAllComponents(ComponentRegistry &registry)
std::set< Component_ptr, std::owner_less< Component_ptr > > Component_set
Definition wire.hpp:54
BusValue busValueFromBits(const std::string_view bits)
Strictly decodes an MSB-first raw string containing 0, 1, X, or E.
std::string documentPathForSlug(const DocumentType type, const std::string_view slug)
std::string currentUtcTimestamp()
Returns the current UTC timestamp formatted as YYYY-MM-DDTHH\:MM\:SSZ.
constexpr int FORMAT_VERSION
Current version of the Silicon project archive schema.
ProjectFile readProjectFile(const std::filesystem::path &path)
Reads and validates a Silicon .sil project archive.
void writeProjectFile(const std::filesystem::path &path, const ProjectFile &projectFile)
Writes a Silicon .sil project archive.
const std::string DEFAULT_CIRCUIT_PATH
Default path of the initial circuit JSON file.
std::string serialize(const Circuit &circuit, const std::string_view moduleName)
Serialize a complete Silicon circuit as Yosys write_json-compatible JSON.
Definition netlist.cpp:443
std::string andSubcircuitDocument()
TEST_F(SubcircuitTest, DeserializesSubcircuitSlugProperty)
BusValue valueFor(const Bus &bus, const std::uint64_t value)
Definition tests.hpp:11