SILICON
Loading...
Searching...
No Matches
logic.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
18#include "tests.hpp"
19#include <core/circuit.hpp>
20#include <core/flipflops.hpp>
21#include <core/io.hpp>
22#include <core/simulator.hpp>
23
24#include <functional>
25#include <limits>
26#include <string>
27#include <tuple>
28#include <utility>
29
30using namespace SILICON::core;
31using namespace SILICON::simulation;
32using namespace SILICON::waveform;
33
34namespace {
35void expectBusStates(const Bus& bus, std::initializer_list<State> expected)
36{
37 ASSERT_EQ(bus.size(), expected.size());
38
39 size_t index = 0;
40 for (const State state : expected) {
41 EXPECT_EQ(bus[index]->getCurrentState(), state) << "Bit " << index;
42 ++index;
43 }
44}
45
46class StringListPropertyTestComponent : public Component {
47public:
48 explicit StringListPropertyTestComponent(std::string defaultValue = "DOWN")
49 : Component({}, {})
50 {
51 defineStringListProperty("orientation", std::move(defaultValue),
52 {"UP", "DOWN", "LEFT", "RIGHT"});
53 }
54
55 std::string_view typeName() const override { return "StringListPropertyTest"; }
56 void simulate(Simulator& sim) override {}
57};
58
59class DefaultedInputTestComponent : public Component {
60public:
61 DefaultedInputTestComponent() : Component({Bus{Wire_ptr{}}}, {})
62 {
63 defineUnconnectedInputDefault(0, State::HIGH);
64 }
65
66 [[nodiscard]] State readInput() const { return inputState(0); }
67 std::string_view typeName() const override { return "DefaultedInputTest"; }
68 void simulate(Simulator&) override {}
69};
70
71class CountingNotGate : public NotGate {
72public:
73 using NotGate::NotGate;
74
75 int simulateCount = 0;
76
77 void simulate(Simulator& sim) override
78 {
79 ++simulateCount;
81 }
82};
83
84class ContextRecordingComponent : public Component {
85public:
86 struct Record {
87 bool initialEvaluation = false;
88 std::vector<Bus> changedBuses;
89 std::vector<std::optional<State>> previousInputStates;
90 std::vector<bool> changedInputs;
91 std::vector<Simulator::EdgeType> inputEdges;
92 };
93
94 explicit ContextRecordingComponent(Bus input) : Component({std::move(input)}, {}) {}
95
96 std::string_view typeName() const override { return "ContextRecording"; }
97
98 void simulate(Simulator&) override { ++legacyCallCount; }
99
100 void simulate(Simulator&, const Context& context) override
101 {
102 Record record;
103 record.initialEvaluation = context.initialEvaluation;
104 record.changedBuses = {context.changedBuses.begin(), context.changedBuses.end()};
105 for (const auto& wire : inputs[0]) {
106 record.previousInputStates.push_back(context.previousState(wire));
107 record.changedInputs.push_back(context.changed(wire));
108 record.inputEdges.push_back(Simulator::edgeType(context, wire));
109 }
110 records.push_back(std::move(record));
111 }
112
113 int legacyCallCount = 0;
114 std::vector<Record> records;
115};
116
117class DeltaCycleTestComponent : public Component {
118public:
119 using Action = std::function<void(Simulator&, DeltaCycleTestComponent&)>;
120
121 DeltaCycleTestComponent(std::vector<Bus> inputs, std::vector<Bus> outputs,
122 Action action)
123 : Component(std::move(inputs), std::move(outputs)), action(std::move(action))
124 {
125 }
126
127 std::string_view typeName() const override { return "DeltaCycleTest"; }
128 void simulate(Simulator& sim) override { action(sim, *this); }
129
130private:
131 Action action;
132};
133} // namespace
134
135TEST(SimulatorTest, CyclicComponentsReadOneSnapshotPerDeltaCycle)
136{
137 auto x = std::make_shared<Wire>(State::LOW);
138 auto y = std::make_shared<Wire>(State::HIGH);
139
140 std::vector<std::pair<State, State>> xReads;
141 std::vector<State> yReads;
142 auto xDriver = std::make_shared<DeltaCycleTestComponent>(
143 std::vector<Bus>{Bus{x}, Bus{y}}, std::vector<Bus>{Bus{x}},
144 [&](Simulator& sim, DeltaCycleTestComponent& self) {
145 const auto oldX = x->getCurrentState();
146 const auto oldY = y->getCurrentState();
147 xReads.emplace_back(oldX, oldY);
148 sim.updateWire(x, oldX || oldY, 0, self.weak_from_this());
149 });
150 auto yDriver = std::make_shared<DeltaCycleTestComponent>(
151 std::vector<Bus>{Bus{x}}, std::vector<Bus>{Bus{y}},
152 [&](Simulator& sim, DeltaCycleTestComponent& self) {
153 const auto oldX = x->getCurrentState();
154 yReads.push_back(oldX);
155 sim.updateWire(y, oldX, 0, self.weak_from_this());
156 });
157
158 auto circuit = std::make_shared<Circuit>(Component_set{xDriver, yDriver}, false);
159 Simulator simulator(circuit);
160
161 // x' = x OR y and y' = x: the first commit must be (HIGH, LOW), no matter
162 // which component the execution plan visits first.
163 ASSERT_EQ(xReads.size(), 3);
164 ASSERT_EQ(yReads.size(), 3);
165 EXPECT_EQ(xReads[0], (std::pair{State::LOW, State::HIGH}));
166 EXPECT_EQ(yReads[0], State::LOW);
167 EXPECT_EQ(xReads[1], (std::pair{State::HIGH, State::LOW}));
168 EXPECT_EQ(yReads[1], State::HIGH);
169 EXPECT_EQ(x->getCurrentState(), State::HIGH);
170 EXPECT_EQ(y->getCurrentState(), State::HIGH);
171}
172
173TEST(SimulatorTest, IndependentCyclicStepsKeepSeparateStagingBuffers)
174{
175 auto x = std::make_shared<Wire>(State::LOW);
176 auto y = std::make_shared<Wire>(State::HIGH);
177 auto u = std::make_shared<Wire>(State::HIGH);
178 auto v = std::make_shared<Wire>(State::LOW);
179
180 auto xDriver = std::make_shared<DeltaCycleTestComponent>(
181 std::vector<Bus>{Bus{y}}, std::vector<Bus>{Bus{x}},
182 [x, y](Simulator& sim, DeltaCycleTestComponent& self) {
183 sim.updateWire(x, y->getCurrentState(), 0, self.weak_from_this());
184 });
185 auto yDriver = std::make_shared<DeltaCycleTestComponent>(
186 std::vector<Bus>{Bus{x}}, std::vector<Bus>{Bus{y}},
187 [x, y](Simulator& sim, DeltaCycleTestComponent& self) {
188 sim.updateWire(y, x->getCurrentState() || y->getCurrentState(), 0,
189 self.weak_from_this());
190 });
191 auto uDriver = std::make_shared<DeltaCycleTestComponent>(
192 std::vector<Bus>{Bus{v}}, std::vector<Bus>{Bus{u}},
193 [u, v](Simulator& sim, DeltaCycleTestComponent& self) {
194 sim.updateWire(u, v->getCurrentState(), 0, self.weak_from_this());
195 });
196 auto vDriver = std::make_shared<DeltaCycleTestComponent>(
197 std::vector<Bus>{Bus{u}}, std::vector<Bus>{Bus{v}},
198 [u, v](Simulator& sim, DeltaCycleTestComponent& self) {
199 sim.updateWire(v, u->getCurrentState() && v->getCurrentState(), 0,
200 self.weak_from_this());
201 });
202
203 auto circuit = std::make_shared<Circuit>(
204 Component_set{xDriver, yDriver, uDriver, vDriver}, false);
205 Simulator simulator(circuit);
206
207 EXPECT_EQ(x->getCurrentState(), State::HIGH);
208 EXPECT_EQ(y->getCurrentState(), State::HIGH);
209 EXPECT_EQ(u->getCurrentState(), State::LOW);
210 EXPECT_EQ(v->getCurrentState(), State::LOW);
211}
212
213TEST(SimulatorTest, CancelledCyclicPassDiscardsStagedWrites)
214{
215 auto trigger = std::make_shared<Wire>(State::LOW);
216 auto x = std::make_shared<Wire>(State::LOW);
217 auto y = std::make_shared<Wire>(State::LOW);
218 int writes = 0;
219
220 auto xDriver = std::make_shared<DeltaCycleTestComponent>(
221 std::vector<Bus>{Bus{trigger}, Bus{y}}, std::vector<Bus>{Bus{x}},
222 [&](Simulator& sim, DeltaCycleTestComponent& self) {
223 if (trigger->getCurrentState() == State::HIGH) {
224 ++writes;
225 sim.updateWire(x, State::HIGH, 0, self.weak_from_this());
226 }
227 });
228 auto yDriver = std::make_shared<DeltaCycleTestComponent>(
229 std::vector<Bus>{Bus{x}}, std::vector<Bus>{Bus{y}},
230 [&](Simulator& sim, DeltaCycleTestComponent& self) {
231 if (trigger->getCurrentState() == State::HIGH) {
232 ++writes;
233 sim.updateWire(y, State::HIGH, 0, self.weak_from_this());
234 }
235 });
236
237 auto circuit = std::make_shared<Circuit>(Component_set{xDriver, yDriver}, false);
238 Simulator simulator(circuit);
239 EXPECT_EQ(simulator.setBus(Bus{trigger}, BusValue{State::HIGH},
240 [&]() { return writes > 0; }),
242 EXPECT_EQ(x->getCurrentState(), State::LOW);
243 EXPECT_EQ(y->getCurrentState(), State::LOW);
244
245 EXPECT_EQ(simulator.setBus(Bus{trigger}, BusValue{State::LOW}),
247 EXPECT_EQ(x->getCurrentState(), State::LOW);
248 EXPECT_EQ(simulator.setBus(Bus{trigger}, BusValue{State::HIGH}),
250 EXPECT_EQ(x->getCurrentState(), State::HIGH);
251 EXPECT_EQ(y->getCurrentState(), State::HIGH);
252}
253
254TEST(SimulatorTest, CyclicConflictingDriversLeaveWireInError)
255{
256 auto x = std::make_shared<Wire>(State::LOW);
257 auto y = std::make_shared<Wire>(State::LOW);
258
259 auto first = std::make_shared<DeltaCycleTestComponent>(
260 std::vector<Bus>{Bus{y}}, std::vector<Bus>{Bus{x}},
261 [x](Simulator& sim, DeltaCycleTestComponent& self) {
262 sim.updateWire(x, State::HIGH, 0, self.weak_from_this());
263 });
264 auto second = std::make_shared<DeltaCycleTestComponent>(
265 std::vector<Bus>{Bus{x}}, std::vector<Bus>{Bus{x}, Bus{y}},
266 [x, y](Simulator& sim, DeltaCycleTestComponent& self) {
267 // This write equals the initial value, but still conflicts with first.
268 sim.updateWire(x, State::LOW, 0, self.weak_from_this());
269 sim.updateWire(y, State::HIGH, 0, self.weak_from_this());
270 });
271
272 x->forceSetCurrentState(State::LOW, second);
273 auto circuit = std::make_shared<Circuit>(Component_set{first, second}, false);
274 Simulator simulator(circuit);
275
276 EXPECT_EQ(x->getCurrentState(), State::ERROR);
277 EXPECT_EQ(y->getCurrentState(), State::HIGH);
278}
279
280TEST(SimulatorTest, RepeatedCyclicWritesByOneSourceKeepItsLastValue)
281{
282 auto x = std::make_shared<Wire>(State::LOW);
283 auto y = std::make_shared<Wire>(State::LOW);
284
285 auto xDriver = std::make_shared<DeltaCycleTestComponent>(
286 std::vector<Bus>{Bus{y}}, std::vector<Bus>{Bus{x}},
287 [x](Simulator& sim, DeltaCycleTestComponent& self) {
288 sim.updateWire(x, State::LOW, 0, self.weak_from_this());
289 sim.updateWire(x, State::HIGH, 0, self.weak_from_this());
290 });
291 auto yDriver = std::make_shared<DeltaCycleTestComponent>(
292 std::vector<Bus>{Bus{x}}, std::vector<Bus>{Bus{y}},
293 [x, y](Simulator& sim, DeltaCycleTestComponent& self) {
294 sim.updateWire(y, x->getCurrentState(), 0, self.weak_from_this());
295 });
296
297 auto circuit = std::make_shared<Circuit>(Component_set{xDriver, yDriver}, false);
298 Simulator simulator(circuit);
299 EXPECT_EQ(x->getCurrentState(), State::HIGH);
300 EXPECT_EQ(y->getCurrentState(), State::HIGH);
301}
302
303TEST(SimulatorTest, PositiveDelayInsideSccUsesEventQueue)
304{
305 auto x = std::make_shared<Wire>(State::LOW);
306 auto y = std::make_shared<Wire>(State::LOW);
307
308 auto immediate = std::make_shared<DeltaCycleTestComponent>(
309 std::vector<Bus>{Bus{y}}, std::vector<Bus>{Bus{x}},
310 [x, y](Simulator& sim, DeltaCycleTestComponent& self) {
311 sim.updateWire(x, !y->getCurrentState(), 0, self.weak_from_this());
312 });
313 auto delayed = std::make_shared<DeltaCycleTestComponent>(
314 std::vector<Bus>{Bus{x}}, std::vector<Bus>{Bus{y}},
315 [x, y](Simulator& sim, DeltaCycleTestComponent& self) {
316 sim.updateWire(y, x->getCurrentState(), 5, self.weak_from_this());
317 });
318
319 auto circuit = std::make_shared<Circuit>(Component_set{immediate, delayed}, false);
320 Simulator simulator(circuit);
321 EXPECT_EQ(x->getCurrentState(), State::HIGH);
322 EXPECT_EQ(y->getCurrentState(), State::LOW);
323 EXPECT_EQ(simulator.run(4), Simulator::RunResult::Completed);
324 EXPECT_EQ(y->getCurrentState(), State::LOW);
325 EXPECT_EQ(simulator.run(1), Simulator::RunResult::Completed);
326 EXPECT_EQ(y->getCurrentState(), State::HIGH);
327 EXPECT_EQ(x->getCurrentState(), State::LOW);
328}
329
330TEST(ConstantComponentTest, DrivesAndResizesBinaryBusValue)
331{
332 Bus output(4);
333 auto constant = std::make_shared<ConstantComponent>(output, busValueFromBits("10X1"));
334 auto circuit = std::make_shared<Circuit>(Component_set{constant}, false);
335
336 Simulator simulator(circuit);
337 ASSERT_EQ(simulator.runUntilIdle(), Simulator::RunResult::Completed);
338 expectBusStates(output, {State::HIGH, State::UNKNOWN, State::LOW, State::HIGH});
339
340 constant->setProperty("size", 6);
341 EXPECT_EQ(constant->outputBuses()[0].size(), 6);
342 EXPECT_EQ(constant->getPropertyValue<BusValue>("value"), busValueFromBits("0010X1"));
343 constant->setProperty("value", BusValue{State::UNKNOWN});
344 EXPECT_EQ(constant->getPropertyValue<BusValue>("value"), BusValue(6, State::UNKNOWN));
345 EXPECT_THROW(constant->setProperty("value", BusValue{State::ERROR}),
346 std::invalid_argument);
347}
348
349TEST(DummyBusInputComponentTest, ResizesValuesWithoutIntegerConversion)
350{
351 auto input = std::make_shared<DummyBusInputComponent>(Bus(4), "input");
352
353 input->setBusValue(busValueFromBits("1"));
354 EXPECT_EQ(input->outputBuses()[0].getCurrentValue(), busValueFromBits("0001"));
355
356 input->setProperty("size", 70);
357 const BusValue wide(70, State::HIGH);
358 input->setBusValue(wide);
359 EXPECT_EQ(input->outputBuses()[0].getCurrentValue(), wide);
360}
361
362TEST(BusValueArithmeticTest, AddsKnownAndFourStateValues)
363{
364 EXPECT_EQ(busValueFromBits("0011") + busValueFromBits("0101"),
365 busValueFromBits("01000"));
366 EXPECT_EQ(busValueFromBits("1111") + busValueFromBits("0001"),
367 busValueFromBits("10000"));
368 EXPECT_EQ(busValueFromBits("11") + busValueFromBits("0001"), busValueFromBits("00100"));
369
372}
373
374TEST(BusValueArithmeticTest, TwosComplementUsesFourStateOperators)
375{
376 EXPECT_EQ(twosComplement(busValueFromBits("0010")), busValueFromBits("1110"));
379 EXPECT_EQ(twosComplement(busValueFromBits("0X")), busValueFromBits("XX"));
380 EXPECT_EQ(twosComplement(busValueFromBits("0E")), busValueFromBits("EE"));
381}
382
383TEST(BusValueArithmeticTest, DivisionPreservesOperandWidths)
384{
385 const auto expectDivision = [](const std::string& dividend, const std::string& divisor,
386 const std::string& quotient,
387 const std::string& remainder) {
388 const auto [actualQuotient, actualRemainder] =
389 divide(busValueFromBits(dividend), busValueFromBits(divisor));
390 EXPECT_EQ(actualQuotient, busValueFromBits(quotient));
391 EXPECT_EQ(actualRemainder, busValueFromBits(remainder));
392 };
393
394 expectDivision("001101", "011", "000100", "001");
395 expectDivision("11", "00101", "00", "00011");
396 expectDivision("0000", "1", "0000", "0");
397 expectDivision("1111", "1", "1111", "0");
398 expectDivision("1111", "0011", "0101", "0000");
399 expectDivision("1", "1", "1", "0");
400}
401
402TEST(BusValueArithmeticTest, DivisionSupportsArbitraryPrecision)
403{
404 const BigInt divisor = (BigInt{1} << 100) + 3;
405 const BigInt quotient = (BigInt{1} << 130) + 5;
406 const BigInt remainder = (BigInt{1} << 80) + 7;
407 const BigInt dividend = divisor * quotient + remainder;
408
409 const auto [actualQuotient, actualRemainder] =
410 divide(busValueFromInteger(dividend, 256), busValueFromInteger(divisor, 128));
411 EXPECT_EQ(actualQuotient, busValueFromInteger(quotient, 256));
412 EXPECT_EQ(actualRemainder, busValueFromInteger(remainder, 128));
413}
414
415TEST(BusValueArithmeticTest, DivisionPropagatesErrorBeforeUnknown)
416{
417 for (const auto& [dividend, divisor, state] :
418 {std::tuple{"00X1", "01", State::UNKNOWN},
419 std::tuple{"0011", "0X", State::UNKNOWN}, std::tuple{"00E1", "0X", State::ERROR},
420 std::tuple{"00X1", "0E", State::ERROR}}) {
421 const auto a = busValueFromBits(dividend);
422 const auto b = busValueFromBits(divisor);
423 const auto [quotient, remainder] = divide(a, b);
424 EXPECT_EQ(quotient, BusValue(a.size(), state));
425 EXPECT_EQ(remainder, BusValue(b.size(), state));
426 }
427}
428
429TEST(BusValueArithmeticTest, DivisionRejectsEmptyOperandsAndZeroDivisors)
430{
431 const auto one = busValueFromBits("1");
432 EXPECT_THROW((void)(divide(BusValue{}, one)), std::invalid_argument);
433 EXPECT_THROW((void)(divide(one, BusValue{})), std::invalid_argument);
434 EXPECT_THROW((void)(divide(BusValue{}, BusValue{})), std::invalid_argument);
435 EXPECT_THROW((void)(divide(one, busValueFromBits("0000"))), std::invalid_argument);
436 EXPECT_THROW((void)(divide(busValueFromBits("X"), busValueFromBits("0"))),
437 std::invalid_argument);
438 EXPECT_THROW((void)(divide(busValueFromBits("E"), busValueFromBits("0"))),
439 std::invalid_argument);
440}
441
442TEST(LogicTest, And)
443{
444 auto a = std::make_shared<Wire>(State::ERROR);
445 auto b = std::make_shared<Wire>(State::ERROR);
446 auto o = std::make_shared<Wire>();
447
448 auto g = std::make_shared<AndGate>(std::vector<Wire_ptr>{a, b}, o);
449 auto circ = std::make_shared<Circuit>(Component_set{g});
450 Simulator sim(circ);
451 sim.run(20); // Process initial zero-delay and gate evaluations
452
453 EXPECT_EQ(o->getCurrentState(), State::ERROR)
454 << "AND(ERROR, ERROR) = " << to_str(o->getCurrentState());
455
456 // Using simulateBus to evaluate the upstream cone for non-standard states
457 b->forceSetCurrentState(State::HIGH);
458 sim.simulateBus(Bus{o});
459 sim.run(20);
460 EXPECT_EQ(o->getCurrentState(), State::ERROR)
461 << "AND(ERROR, HIGH) = " << to_str(o->getCurrentState());
462
463 b->forceSetCurrentState(State::LOW);
464 sim.simulateBus(Bus{o});
465 sim.run(20);
466 EXPECT_EQ(o->getCurrentState(), State::ERROR)
467 << "AND(ERROR, LOW) = " << to_str(o->getCurrentState());
468
469 // Using setBus to reactively propagate inputs through the forward subgraph
470 sim.setBus(Bus{a}, valueFor(Bus{a}, 0)); // LOW
471 sim.setBus(Bus{b}, valueFor(Bus{b}, 0)); // LOW
472 sim.run(20);
473 EXPECT_EQ(o->getCurrentState(), State::LOW)
474 << "AND(LOW, LOW) = " << to_str(o->getCurrentState());
475
476 sim.setBus(Bus{a}, valueFor(Bus{a}, 1)); // HIGH
477 sim.run(20);
478 EXPECT_EQ(o->getCurrentState(), State::LOW)
479 << "AND(HIGH, LOW) = " << to_str(o->getCurrentState());
480
481 sim.setBus(Bus{b}, valueFor(Bus{b}, 1)); // HIGH
482 sim.run(20);
483 EXPECT_EQ(o->getCurrentState(), State::HIGH)
484 << "AND(HIGH, HIGH) = " << to_str(o->getCurrentState());
485}
486
487TEST(SimulatorTest, CancelledRunCanResumePendingEvents)
488{
489 auto a = std::make_shared<Wire>(State::HIGH);
490 auto b = std::make_shared<Wire>(State::HIGH);
491 auto o = std::make_shared<Wire>();
492
493 auto gate = std::make_shared<AndGate>(std::vector<Wire_ptr>{a, b}, o);
494 auto circuit = std::make_shared<Circuit>(Component_set{gate});
495 Simulator simulator(circuit);
496 const auto stateBeforeCancellation = o->getCurrentState();
497
498 EXPECT_EQ(simulator.run(20, []() { return true; }), Simulator::RunResult::Cancelled);
499 EXPECT_EQ(o->getCurrentState(), stateBeforeCancellation);
500
501 EXPECT_EQ(simulator.run(20), Simulator::RunResult::Completed);
502 EXPECT_EQ(o->getCurrentState(), State::HIGH);
503}
504
505TEST(SimulatorTest, CancellationStopsBusPropagation)
506{
507 auto a = std::make_shared<Wire>(State::LOW);
508 auto b = std::make_shared<Wire>(State::HIGH);
509 auto o = std::make_shared<Wire>();
510
511 auto gate = std::make_shared<AndGate>(std::vector<Wire_ptr>{a, b}, o);
512 auto circuit = std::make_shared<Circuit>(Component_set{gate});
513 Simulator simulator(circuit);
514
515 EXPECT_EQ(simulator.setBus(Bus{a}, valueFor(Bus{a}, 1), []() { return true; }),
517 EXPECT_EQ(a->getCurrentState(), State::LOW);
518}
519
520TEST(SimulatorTest, PassesSimulationContextToComponents)
521{
522 auto lowBit = std::make_shared<Wire>(State::LOW);
523 auto highBit = std::make_shared<Wire>(State::LOW);
524 Bus input{lowBit, highBit};
525
526 auto recorder = std::make_shared<ContextRecordingComponent>(input);
527 auto circuit = std::make_shared<Circuit>(Component_set{recorder});
528 Simulator simulator(circuit);
529
530 ASSERT_EQ(recorder->records.size(), 1);
531 EXPECT_TRUE(recorder->records[0].initialEvaluation);
532 EXPECT_TRUE(recorder->records[0].changedBuses.empty());
533 EXPECT_EQ(recorder->legacyCallCount, 0);
534
535 EXPECT_EQ(simulator.setBus(input, valueFor(input, 1)), Simulator::RunResult::Completed);
536
537 ASSERT_EQ(recorder->records.size(), 2);
538 EXPECT_FALSE(recorder->records[1].initialEvaluation);
539 ASSERT_EQ(recorder->records[1].changedBuses.size(), 1);
540 ASSERT_EQ(recorder->records[1].changedBuses[0].size(), 2);
541 EXPECT_EQ(recorder->records[1].changedBuses[0][0], lowBit);
542 EXPECT_EQ(recorder->records[1].changedBuses[0][1], highBit);
543 ASSERT_EQ(recorder->records[1].previousInputStates.size(), 2);
544 ASSERT_TRUE(recorder->records[1].previousInputStates[0].has_value());
545 ASSERT_TRUE(recorder->records[1].previousInputStates[1].has_value());
546 EXPECT_EQ(*recorder->records[1].previousInputStates[0], State::LOW);
547 EXPECT_EQ(*recorder->records[1].previousInputStates[1], State::LOW);
548 EXPECT_EQ(recorder->records[1].changedInputs, (std::vector<bool>{true, false}));
549 EXPECT_EQ(recorder->records[1].inputEdges,
550 (std::vector<Simulator::EdgeType>{Simulator::EdgeType::RISE,
551 Simulator::EdgeType::NO_CHANGE}));
552
553 EXPECT_EQ(simulator.setBus(input, valueFor(input, 0)), Simulator::RunResult::Completed);
554
555 ASSERT_EQ(recorder->records.size(), 3);
556 EXPECT_EQ(recorder->records[2].inputEdges,
557 (std::vector<Simulator::EdgeType>{Simulator::EdgeType::FALL,
558 Simulator::EdgeType::NO_CHANGE}));
559}
560
561TEST(SimulatorTest, DelayedEventBatchCapturesPreviousStateBeforeApplyingEvents)
562{
563 auto a = std::make_shared<Wire>(State::LOW);
564 auto b = std::make_shared<Wire>(State::HIGH);
565 auto x = std::make_shared<Wire>(State::UNKNOWN);
566 auto y = std::make_shared<Wire>(State::UNKNOWN);
567
568 auto xDriver = std::make_shared<NotGate>(a, x);
569 auto yDriver = std::make_shared<NotGate>(b, y);
570 xDriver->setProperty("delay", 5);
571 yDriver->setProperty("delay", 5);
572
573 auto recorder = std::make_shared<ContextRecordingComponent>(Bus{x, y});
574 auto circuit = std::make_shared<Circuit>(Component_set{xDriver, yDriver, recorder});
575 Simulator simulator(circuit);
576
577 EXPECT_EQ(simulator.run(5), Simulator::RunResult::Completed);
578
579 ASSERT_GE(recorder->records.size(), 2);
580 const auto& delayedRecord = recorder->records.back();
581 EXPECT_FALSE(delayedRecord.initialEvaluation);
582 ASSERT_EQ(delayedRecord.previousInputStates.size(), 2);
583 ASSERT_TRUE(delayedRecord.previousInputStates[0].has_value());
584 ASSERT_TRUE(delayedRecord.previousInputStates[1].has_value());
585 EXPECT_EQ(*delayedRecord.previousInputStates[0], State::UNKNOWN);
586 EXPECT_EQ(*delayedRecord.previousInputStates[1], State::UNKNOWN);
587 EXPECT_EQ(delayedRecord.changedInputs, (std::vector<bool>{true, true}));
588 EXPECT_EQ(delayedRecord.inputEdges,
589 (std::vector<Simulator::EdgeType>{Simulator::EdgeType::UNKNOWN,
590 Simulator::EdgeType::UNKNOWN}));
591 EXPECT_EQ(x->getCurrentState(), State::HIGH);
592 EXPECT_EQ(y->getCurrentState(), State::LOW);
593}
594
595TEST(SimulatorTest, SimulatesInternalInputWaveform)
596{
597 auto a = std::make_shared<Wire>(State::LOW);
598 auto b = std::make_shared<Wire>(State::LOW);
599 auto o = std::make_shared<Wire>();
600
601 auto gate = std::make_shared<AndGate>(std::vector<Wire_ptr>{a, b}, o);
602 auto circuit = std::make_shared<Circuit>(Component_set{gate});
603 Simulator simulator(circuit);
604
605 const std::vector<Sample> inputSnapshots{
606 {0, {busValueFromBits("0"), busValueFromBits("0")}},
607 {3, {busValueFromBits("1"), busValueFromBits("1")}},
608 };
609 const std::vector<Simulator::WaveformInputDriver> inputDrivers{
610 {Bus{a}, {}},
611 {Bus{b}, {}},
612 };
613
614 EXPECT_EQ(simulator.simulateWaveform(10, inputSnapshots, inputDrivers),
616 EXPECT_EQ(simulator.getCurrentTime(), 10);
617 EXPECT_EQ(o->getCurrentState(), State::HIGH);
618}
619
620TEST(SimulatorTest, WaveformInputSampleCapturesPreviousWireStates)
621{
622 auto lowBit = std::make_shared<Wire>(State::LOW);
623 auto highBit = std::make_shared<Wire>(State::LOW);
624 Bus input{lowBit, highBit};
625
626 auto recorder = std::make_shared<ContextRecordingComponent>(input);
627 auto circuit = std::make_shared<Circuit>(Component_set{recorder});
628 Simulator simulator(circuit);
629
630 const std::vector<Sample> inputSnapshots{{0, {busValueFromBits("01")}}};
631 const std::vector<Simulator::WaveformInputDriver> inputDrivers{{input, {}}};
632
633 EXPECT_EQ(simulator.simulateWaveform(1, inputSnapshots, inputDrivers),
635
636 ASSERT_EQ(recorder->records.size(), 2);
637 const auto& sampleRecord = recorder->records[1];
638 EXPECT_FALSE(sampleRecord.initialEvaluation);
639 ASSERT_EQ(sampleRecord.previousInputStates.size(), 2);
640 ASSERT_TRUE(sampleRecord.previousInputStates[0].has_value());
641 ASSERT_TRUE(sampleRecord.previousInputStates[1].has_value());
642 EXPECT_EQ(*sampleRecord.previousInputStates[0], State::LOW);
643 EXPECT_EQ(*sampleRecord.previousInputStates[1], State::LOW);
644 EXPECT_EQ(sampleRecord.changedInputs, (std::vector<bool>{true, false}));
645 EXPECT_EQ(sampleRecord.inputEdges,
646 (std::vector<Simulator::EdgeType>{Simulator::EdgeType::RISE,
647 Simulator::EdgeType::NO_CHANGE}));
648}
649
650TEST(SimulatorTest, WaveformDoesNotPropagateWhenNormalizedValueIsUnchanged)
651{
652 auto lowBit = std::make_shared<Wire>(State::HIGH);
653 auto highBit = std::make_shared<Wire>(State::LOW);
654 Bus input{lowBit, highBit};
655
656 auto recorder = std::make_shared<ContextRecordingComponent>(input);
657 auto circuit = std::make_shared<Circuit>(Component_set{recorder});
658 Simulator simulator(circuit);
659 ASSERT_EQ(simulator.runUntilIdle(), Simulator::RunResult::Completed);
660 const auto recordsBeforeSample = recorder->records.size();
661
662 const std::vector<Sample> inputSnapshots{{0, {busValueFromBits("1")}}};
663 const std::vector<Simulator::WaveformInputDriver> inputDrivers{{input, {}}};
664
665 EXPECT_EQ(simulator.simulateWaveform(1, inputSnapshots, inputDrivers),
667 EXPECT_EQ(recorder->records.size(), recordsBeforeSample);
668 EXPECT_EQ(input.getCurrentValue(), busValueFromBits("01"));
669}
670
671TEST(SimulatorTest, UpdateBusRequiresExactWidthForImmediateAndDelayedValues)
672{
673 Bus bus(3);
674 auto circuit = std::make_shared<Circuit>();
675 Simulator simulator(circuit);
676
677 EXPECT_THROW(simulator.updateBus(bus, busValueFromBits("1"), 0, {}),
678 std::invalid_argument);
679
680 simulator.updateBus(bus, busValueFromBits("001"), 0, {});
681 EXPECT_EQ(bus.getCurrentValue(), busValueFromBits("001"));
682
683 EXPECT_THROW(simulator.updateBus(bus, busValueFromBits("10"), 3, {}),
684 std::invalid_argument);
685
686 simulator.updateBus(bus, busValueFromBits("010"), 3, {});
687 EXPECT_EQ(bus.getCurrentValue(), busValueFromBits("001"));
688 EXPECT_EQ(simulator.run(2), Simulator::RunResult::Completed);
689 EXPECT_EQ(bus.getCurrentValue(), busValueFromBits("001"));
690 EXPECT_EQ(simulator.run(1), Simulator::RunResult::Completed);
691 EXPECT_EQ(bus.getCurrentValue(), busValueFromBits("010"));
692}
693
694TEST(SimulatorTest, DelayedGateRejectsShortInputPulse)
695{
696 auto a = std::make_shared<Wire>(State::LOW);
697 auto b = std::make_shared<Wire>(State::HIGH);
698 auto o = std::make_shared<Wire>(State::LOW);
699
700 auto gate = std::make_shared<AndGate>(std::vector<Wire_ptr>{a, b}, o);
701 gate->setProperty("delay", 10);
702
703 auto circuit = std::make_shared<Circuit>(Component_set{gate});
704 Simulator simulator(circuit);
705
706 EXPECT_EQ(simulator.setBus(Bus{a}, valueFor(Bus{a}, 1)),
708 EXPECT_EQ(simulator.run(5), Simulator::RunResult::Completed);
709 EXPECT_EQ(simulator.setBus(Bus{a}, valueFor(Bus{a}, 0)),
711 EXPECT_EQ(simulator.run(20), Simulator::RunResult::Completed);
712
713 EXPECT_EQ(o->getCurrentState(), State::LOW);
714}
715
716TEST(SimulatorTest, DelayedGateReplacesPendingTransition)
717{
718 auto a = std::make_shared<Wire>(State::LOW);
719 auto b = std::make_shared<Wire>(State::HIGH);
720 auto o = std::make_shared<Wire>(State::UNKNOWN);
721
722 auto gate = std::make_shared<AndGate>(std::vector<Wire_ptr>{a, b}, o);
723 gate->setProperty("delay", 10);
724
725 auto circuit = std::make_shared<Circuit>(Component_set{gate});
726 Simulator simulator(circuit);
727
728 EXPECT_EQ(simulator.run(5), Simulator::RunResult::Completed);
729 EXPECT_EQ(simulator.setBus(Bus{a}, valueFor(Bus{a}, 1)),
731 EXPECT_EQ(simulator.run(5), Simulator::RunResult::Completed);
732 EXPECT_EQ(o->getCurrentState(), State::UNKNOWN);
733
734 EXPECT_EQ(simulator.run(5), Simulator::RunResult::Completed);
735 EXPECT_EQ(o->getCurrentState(), State::HIGH);
736}
737
738TEST(SimulatorTest, DelayedGateReevaluationDoesNotPostponePendingTransition)
739{
740 auto input = std::make_shared<Wire>(State::LOW);
741 auto inverted = std::make_shared<Wire>(State::UNKNOWN);
742 auto output = std::make_shared<Wire>(State::UNKNOWN);
743
744 auto notGate = std::make_shared<CountingNotGate>(input, inverted);
745 notGate->setProperty("delay", 7);
746
747 auto andGate =
748 std::make_shared<AndGate>(std::vector<Wire_ptr>{input, inverted}, output);
749 andGate->setProperty("delay", 5);
750
751 auto circuit = std::make_shared<Circuit>(Component_set{notGate, andGate});
752 Simulator simulator(circuit);
753
754 EXPECT_EQ(simulator.run(5), Simulator::RunResult::Completed);
755 EXPECT_EQ(output->getCurrentState(), State::LOW);
756 EXPECT_EQ(inverted->getCurrentState(), State::UNKNOWN);
757 EXPECT_EQ(notGate->simulateCount, 1);
758
759 EXPECT_EQ(simulator.run(2), Simulator::RunResult::Completed);
760 EXPECT_EQ(inverted->getCurrentState(), State::HIGH);
761 EXPECT_EQ(notGate->simulateCount, 1);
762}
763
764TEST(SimulatorTest, ForwardPropagationDoesNotRescheduleIndependentDelayedBranch)
765{
766 auto a1 = std::make_shared<Wire>(State::HIGH);
767 auto b1 = std::make_shared<Wire>(State::HIGH);
768 auto o1 = std::make_shared<Wire>(State::UNKNOWN);
769
770 auto a2 = std::make_shared<Wire>(State::HIGH);
771 auto b2 = std::make_shared<Wire>(State::HIGH);
772 auto o2 = std::make_shared<Wire>(State::UNKNOWN);
773
774 auto first = std::make_shared<AndGate>(std::vector<Wire_ptr>{a1, b1}, o1);
775 first->setProperty("delay", 10);
776
777 auto second = std::make_shared<AndGate>(std::vector<Wire_ptr>{a2, b2}, o2);
778 second->setProperty("delay", 10);
779
780 auto circuit = std::make_shared<Circuit>(Component_set{first, second});
781 Simulator simulator(circuit);
782
783 EXPECT_EQ(simulator.run(5), Simulator::RunResult::Completed);
784 EXPECT_EQ(simulator.setBus(Bus{a1}, valueFor(Bus{a1}, 0)),
786
787 EXPECT_EQ(simulator.run(5), Simulator::RunResult::Completed);
788 EXPECT_EQ(o1->getCurrentState(), State::UNKNOWN);
789 EXPECT_EQ(o2->getCurrentState(), State::HIGH);
790}
791
792TEST(SimulatorTest, RunUntilIdlePropagatesThroughLongDelayChain)
793{
794 auto a = std::make_shared<Wire>(State::HIGH);
795 auto b = std::make_shared<Wire>(State::HIGH);
796 auto c = std::make_shared<Wire>(State::HIGH);
797 auto w = std::make_shared<Wire>(State::UNKNOWN);
798 auto o = std::make_shared<Wire>(State::UNKNOWN);
799
800 auto first = std::make_shared<AndGate>(std::vector<Wire_ptr>{a, b}, w);
801 first->setProperty("delay", 50);
802
803 auto second = std::make_shared<AndGate>(std::vector<Wire_ptr>{w, c}, o);
804 second->setProperty("delay", 50);
805
806 auto circuit = std::make_shared<Circuit>(Component_set{first, second});
807 Simulator simulator(circuit);
808
809 EXPECT_EQ(simulator.runUntilIdle(), Simulator::RunResult::Completed);
810 EXPECT_EQ(simulator.getCurrentTime(), 100);
811 EXPECT_EQ(o->getCurrentState(), State::HIGH);
812}
813
814TEST(SimulatorTest, RunUntilIdleStopsAtStepLimitForDelayedFeedback)
815{
816 const auto previousMaxSimulationSteps = Simulator::getMaxSimulationSteps();
818
819 auto wire = std::make_shared<Wire>(State::LOW);
820 auto gate = std::make_shared<NotGate>(wire, wire);
821 gate->setProperty("delay", 1);
822
823 auto circuit = std::make_shared<Circuit>(Component_set{gate});
824 Simulator simulator(circuit);
825
826 EXPECT_EQ(simulator.runUntilIdle(), Simulator::RunResult::StepLimitReached);
827 EXPECT_EQ(simulator.getCurrentTime(), 3);
828
829 Simulator::setMaxSimulationSteps(previousMaxSimulationSteps);
830}
831
832TEST(FlipFlopTest, DFlipFlopCapturesOnPositiveEdge)
833{
834 auto d = std::make_shared<Wire>(State::LOW);
835 auto clock = std::make_shared<Wire>(State::LOW);
836 auto clear = std::make_shared<Wire>(State::LOW);
837 auto preset = std::make_shared<Wire>(State::LOW);
838 auto q = std::make_shared<Wire>(State::UNKNOWN);
839 auto notQ = std::make_shared<Wire>(State::UNKNOWN);
840
841 auto flipFlop = std::make_shared<DFlipFlop>(d, clock, clear, preset, q, notQ);
842 flipFlop->setProperty("propagationDelay", 0);
843
844 auto circuit = std::make_shared<Circuit>(Component_set{flipFlop});
845 Simulator simulator(circuit);
846
847 EXPECT_EQ(simulator.setBus(Bus{d}, valueFor(Bus{d}, 1)),
849 EXPECT_EQ(q->getCurrentState(), State::UNKNOWN);
850
851 EXPECT_EQ(simulator.setBus(Bus{clock}, valueFor(Bus{clock}, 1)),
853 EXPECT_EQ(q->getCurrentState(), State::HIGH);
854 EXPECT_EQ(notQ->getCurrentState(), State::LOW);
855
856 EXPECT_EQ(simulator.setBus(Bus{d}, valueFor(Bus{d}, 0)),
858 EXPECT_EQ(q->getCurrentState(), State::HIGH);
859
860 EXPECT_EQ(simulator.setBus(Bus{clock}, valueFor(Bus{clock}, 0)),
862 EXPECT_EQ(q->getCurrentState(), State::HIGH);
863
864 EXPECT_EQ(simulator.setBus(Bus{clock}, valueFor(Bus{clock}, 1)),
866 EXPECT_EQ(q->getCurrentState(), State::LOW);
867 EXPECT_EQ(notQ->getCurrentState(), State::HIGH);
868}
869
870TEST(FlipFlopTest, DFlipFlopCapturesOnNegativeEdge)
871{
872 auto d = std::make_shared<Wire>(State::LOW);
873 auto clock = std::make_shared<Wire>(State::HIGH);
874 auto clear = std::make_shared<Wire>(State::LOW);
875 auto preset = std::make_shared<Wire>(State::LOW);
876 auto q = std::make_shared<Wire>(State::UNKNOWN);
877 auto notQ = std::make_shared<Wire>(State::UNKNOWN);
878
879 auto flipFlop = std::make_shared<DFlipFlop>(d, clock, clear, preset, q, notQ);
880 flipFlop->setProperty("propagationDelay", 0);
881 flipFlop->setProperty("triggerEdge", std::string("NET"));
882
883 auto circuit = std::make_shared<Circuit>(Component_set{flipFlop});
884 Simulator simulator(circuit);
885
886 EXPECT_EQ(simulator.setBus(Bus{d}, valueFor(Bus{d}, 1)),
888 EXPECT_EQ(simulator.setBus(Bus{clock}, valueFor(Bus{clock}, 0)),
890 EXPECT_EQ(q->getCurrentState(), State::HIGH);
891 EXPECT_EQ(notQ->getCurrentState(), State::LOW);
892
893 EXPECT_EQ(simulator.setBus(Bus{d}, valueFor(Bus{d}, 0)),
895 EXPECT_EQ(simulator.setBus(Bus{clock}, valueFor(Bus{clock}, 1)),
897 EXPECT_EQ(q->getCurrentState(), State::HIGH);
898
899 EXPECT_EQ(simulator.setBus(Bus{clock}, valueFor(Bus{clock}, 0)),
901 EXPECT_EQ(q->getCurrentState(), State::LOW);
902 EXPECT_EQ(notQ->getCurrentState(), State::HIGH);
903}
904
905TEST(FlipFlopTest, EFlipFlopHonorsEnable)
906{
907 auto d = std::make_shared<Wire>(State::HIGH);
908 auto enable = std::make_shared<Wire>(State::LOW);
909 auto clock = std::make_shared<Wire>(State::LOW);
910 auto clear = std::make_shared<Wire>(State::LOW);
911 auto preset = std::make_shared<Wire>(State::LOW);
912 auto q = std::make_shared<Wire>(State::UNKNOWN);
913 auto notQ = std::make_shared<Wire>(State::UNKNOWN);
914
915 auto flipFlop = std::make_shared<EFlipFlop>(d, enable, clock, clear, preset, q, notQ);
916 flipFlop->setProperty("propagationDelay", 0);
917 auto circuit = std::make_shared<Circuit>(Component_set{flipFlop});
918 Simulator simulator(circuit);
919
920 EXPECT_EQ(simulator.setBus(Bus{clock}, valueFor(Bus{clock}, 1)),
922 EXPECT_EQ(q->getCurrentState(), State::UNKNOWN);
923
924 EXPECT_EQ(simulator.setBus(Bus{clock}, valueFor(Bus{clock}, 0)),
926 EXPECT_EQ(simulator.setBus(Bus{enable}, valueFor(Bus{enable}, 1)),
928 EXPECT_EQ(simulator.setBus(Bus{clock}, valueFor(Bus{clock}, 1)),
930 EXPECT_EQ(q->getCurrentState(), State::HIGH);
931 EXPECT_EQ(notQ->getCurrentState(), State::LOW);
932
933 EXPECT_EQ(simulator.setBus(Bus{clock}, valueFor(Bus{clock}, 0)),
935 EXPECT_EQ(simulator.setBus(Bus{enable}, valueFor(Bus{enable}, 0)),
937 EXPECT_EQ(simulator.setBus(Bus{d}, valueFor(Bus{d}, 0)),
939 EXPECT_EQ(simulator.setBus(Bus{clock}, valueFor(Bus{clock}, 1)),
941 EXPECT_EQ(q->getCurrentState(), State::HIGH);
942 EXPECT_EQ(notQ->getCurrentState(), State::LOW);
943}
944
945TEST(FlipFlopTest, DLatchIsTransparentWhileEnabledAndHoldsWhileDisabled)
946{
947 auto d = std::make_shared<Wire>(State::LOW);
948 auto enable = std::make_shared<Wire>(State::LOW);
949 auto q = std::make_shared<Wire>(State::UNKNOWN);
950 auto notQ = std::make_shared<Wire>(State::UNKNOWN);
951
952 auto latch = std::make_shared<DLatch>(d, enable, q, notQ);
953 latch->setProperty("propagationDelay", 0);
954
955 auto circuit = std::make_shared<Circuit>(Component_set{latch});
956 Simulator simulator(circuit);
957
958 EXPECT_EQ(simulator.setBus(Bus{d}, valueFor(Bus{d}, 1)),
960 EXPECT_EQ(q->getCurrentState(), State::UNKNOWN);
961 EXPECT_EQ(notQ->getCurrentState(), State::UNKNOWN);
962
963 EXPECT_EQ(simulator.setBus(Bus{enable}, valueFor(Bus{enable}, 1)),
965 EXPECT_EQ(q->getCurrentState(), State::HIGH);
966 EXPECT_EQ(notQ->getCurrentState(), State::LOW);
967
968 EXPECT_EQ(simulator.setBus(Bus{d}, valueFor(Bus{d}, 0)),
970 EXPECT_EQ(q->getCurrentState(), State::LOW);
971 EXPECT_EQ(notQ->getCurrentState(), State::HIGH);
972
973 EXPECT_EQ(simulator.setBus(Bus{enable}, valueFor(Bus{enable}, 0)),
975 EXPECT_EQ(simulator.setBus(Bus{d}, valueFor(Bus{d}, 1)),
977 EXPECT_EQ(q->getCurrentState(), State::LOW);
978 EXPECT_EQ(notQ->getCurrentState(), State::HIGH);
979}
980
981TEST(FlipFlopTest, DLatchUnknownEnableInvalidatesStoredState)
982{
983 auto d = std::make_shared<Wire>(State::HIGH);
984 auto enable = std::make_shared<Wire>(State::HIGH);
985 auto q = std::make_shared<Wire>(State::UNKNOWN);
986 auto notQ = std::make_shared<Wire>(State::UNKNOWN);
987
988 auto latch = std::make_shared<DLatch>(d, enable, q, notQ);
989 latch->setProperty("propagationDelay", 0);
990
991 auto circuit = std::make_shared<Circuit>(Component_set{latch});
992 Simulator simulator(circuit);
993 ASSERT_EQ(simulator.runUntilIdle(), Simulator::RunResult::Completed);
994 ASSERT_EQ(q->getCurrentState(), State::HIGH);
995
996 enable->setCurrentState(State::UNKNOWN, {});
997 const std::array changedBuses{Bus{enable}};
998 latch->simulate(simulator,
999 Context{false, changedBuses, {{enable->getId(), State::HIGH}}});
1000 EXPECT_EQ(q->getCurrentState(), State::UNKNOWN);
1001 EXPECT_EQ(notQ->getCurrentState(), State::UNKNOWN);
1002}
1003
1004TEST(FlipFlopTest, DLatchPropagationDelayDefersTransparentUpdates)
1005{
1006 auto d = std::make_shared<Wire>(State::HIGH);
1007 auto enable = std::make_shared<Wire>(State::LOW);
1008 auto q = std::make_shared<Wire>(State::UNKNOWN);
1009 auto notQ = std::make_shared<Wire>(State::UNKNOWN);
1010
1011 auto latch = std::make_shared<DLatch>(d, enable, q, notQ);
1012 EXPECT_EQ(latch->getPropertyValue<int>("propagationDelay"), 5);
1013 EXPECT_THROW(latch->setProperty("propagationDelay", -1), std::invalid_argument);
1014
1015 auto circuit = std::make_shared<Circuit>(Component_set{latch});
1016 Simulator simulator(circuit);
1017
1018 EXPECT_EQ(simulator.setBus(Bus{enable}, valueFor(Bus{enable}, 1)),
1020 EXPECT_EQ(q->getCurrentState(), State::UNKNOWN);
1021 EXPECT_EQ(simulator.run(4), Simulator::RunResult::Completed);
1022 EXPECT_EQ(q->getCurrentState(), State::UNKNOWN);
1023 EXPECT_EQ(simulator.run(1), Simulator::RunResult::Completed);
1024 EXPECT_EQ(q->getCurrentState(), State::HIGH);
1025 EXPECT_EQ(notQ->getCurrentState(), State::LOW);
1026}
1027
1028TEST(FlipFlopTest, JKFlipFlopImplementsTruthTable)
1029{
1030 auto j = std::make_shared<Wire>(State::LOW);
1031 auto k = std::make_shared<Wire>(State::LOW);
1032 auto clock = std::make_shared<Wire>(State::LOW);
1033 auto clear = std::make_shared<Wire>(State::LOW);
1034 auto preset = std::make_shared<Wire>(State::LOW);
1035 auto q = std::make_shared<Wire>(State::UNKNOWN);
1036 auto notQ = std::make_shared<Wire>(State::UNKNOWN);
1037
1038 auto flipFlop = std::make_shared<JKFlipFlop>(j, k, clock, clear, preset, q, notQ);
1039 flipFlop->setProperty("propagationDelay", 0);
1040
1041 auto circuit = std::make_shared<Circuit>(Component_set{flipFlop});
1042 Simulator simulator(circuit);
1043
1044 EXPECT_EQ(simulator.setBus(Bus{j}, valueFor(Bus{j}, 1)),
1046 EXPECT_EQ(simulator.setBus(Bus{k}, valueFor(Bus{k}, 0)),
1048 EXPECT_EQ(simulator.setBus(Bus{clock}, valueFor(Bus{clock}, 1)),
1050 EXPECT_EQ(q->getCurrentState(), State::HIGH);
1051
1052 EXPECT_EQ(simulator.setBus(Bus{clock}, valueFor(Bus{clock}, 0)),
1054 EXPECT_EQ(simulator.setBus(Bus{j}, valueFor(Bus{j}, 0)),
1056 EXPECT_EQ(simulator.setBus(Bus{k}, valueFor(Bus{k}, 0)),
1058 EXPECT_EQ(simulator.setBus(Bus{clock}, valueFor(Bus{clock}, 1)),
1060 EXPECT_EQ(q->getCurrentState(), State::HIGH);
1061
1062 EXPECT_EQ(simulator.setBus(Bus{clock}, valueFor(Bus{clock}, 0)),
1064 EXPECT_EQ(simulator.setBus(Bus{k}, valueFor(Bus{k}, 1)),
1066 EXPECT_EQ(simulator.setBus(Bus{clock}, valueFor(Bus{clock}, 1)),
1068 EXPECT_EQ(q->getCurrentState(), State::LOW);
1069
1070 EXPECT_EQ(simulator.setBus(Bus{clock}, valueFor(Bus{clock}, 0)),
1072 EXPECT_EQ(simulator.setBus(Bus{j}, valueFor(Bus{j}, 1)),
1074 EXPECT_EQ(simulator.setBus(Bus{clock}, valueFor(Bus{clock}, 1)),
1076 EXPECT_EQ(q->getCurrentState(), State::HIGH);
1077 EXPECT_EQ(notQ->getCurrentState(), State::LOW);
1078
1079 EXPECT_EQ(simulator.setBus(Bus{clock}, valueFor(Bus{clock}, 0)),
1081 EXPECT_EQ(simulator.setBus(Bus{clock}, valueFor(Bus{clock}, 1)),
1083 EXPECT_EQ(q->getCurrentState(), State::LOW);
1084 EXPECT_EQ(notQ->getCurrentState(), State::HIGH);
1085}
1086
1087TEST(FlipFlopTest, AsyncClearAndPresetOverrideInputs)
1088{
1089 auto d = std::make_shared<Wire>(State::HIGH);
1090 auto clock = std::make_shared<Wire>(State::LOW);
1091 auto clear = std::make_shared<Wire>(State::LOW);
1092 auto preset = std::make_shared<Wire>(State::LOW);
1093 auto q = std::make_shared<Wire>(State::UNKNOWN);
1094 auto notQ = std::make_shared<Wire>(State::UNKNOWN);
1095
1096 auto flipFlop = std::make_shared<DFlipFlop>(d, clock, clear, preset, q, notQ);
1097 flipFlop->setProperty("propagationDelay", 0);
1098
1099 auto circuit = std::make_shared<Circuit>(Component_set{flipFlop});
1100 Simulator simulator(circuit);
1101
1102 EXPECT_EQ(simulator.setBus(Bus{clear}, valueFor(Bus{clear}, 1)),
1104 EXPECT_EQ(q->getCurrentState(), State::LOW);
1105 EXPECT_EQ(notQ->getCurrentState(), State::HIGH);
1106
1107 EXPECT_EQ(simulator.setBus(Bus{clear}, valueFor(Bus{clear}, 0)),
1109 EXPECT_EQ(simulator.setBus(Bus{preset}, valueFor(Bus{preset}, 1)),
1111 EXPECT_EQ(q->getCurrentState(), State::HIGH);
1112 EXPECT_EQ(notQ->getCurrentState(), State::LOW);
1113
1114 EXPECT_EQ(simulator.setBus(Bus{clear}, valueFor(Bus{clear}, 1)),
1116 EXPECT_EQ(q->getCurrentState(), State::UNKNOWN);
1117 EXPECT_EQ(notQ->getCurrentState(), State::UNKNOWN);
1118}
1119
1120TEST(FlipFlopTest, UnconnectedAsyncControlsDefaultInactive)
1121{
1122 auto d = std::make_shared<Wire>(State::HIGH);
1123 auto clock = std::make_shared<Wire>(State::LOW);
1124 auto q = std::make_shared<Wire>(State::UNKNOWN);
1125 auto notQ = std::make_shared<Wire>(State::UNKNOWN);
1126
1127 auto flipFlop = std::make_shared<DFlipFlop>(d, clock, Wire_ptr{}, Wire_ptr{}, q, notQ);
1128 flipFlop->setProperty("propagationDelay", 0);
1129 EXPECT_EQ(
1130 flipFlop->unconnectedInputDefault(std::to_underlying(DFlipFlop::Inputs::Clear)),
1131 State::LOW);
1132 EXPECT_EQ(
1133 flipFlop->unconnectedInputDefault(std::to_underlying(DFlipFlop::Inputs::Preset)),
1134 State::LOW);
1135
1136 auto circuit = std::make_shared<Circuit>(Component_set{flipFlop});
1137 Simulator simulator(circuit);
1138
1139 EXPECT_EQ(simulator.setBus(Bus{clock}, valueFor(Bus{clock}, 1)),
1141 EXPECT_EQ(q->getCurrentState(), State::HIGH);
1142 EXPECT_EQ(notQ->getCurrentState(), State::LOW);
1143}
1144
1145TEST(FlipFlopTest, UnconnectedAsyncControlsRemainInactiveAfterClearingWires)
1146{
1147 auto d = std::make_shared<Wire>(State::HIGH);
1148 auto clock = std::make_shared<Wire>(State::LOW);
1149 auto q = std::make_shared<Wire>(State::UNKNOWN);
1150 auto notQ = std::make_shared<Wire>(State::UNKNOWN);
1151
1152 auto flipFlop = std::make_shared<DFlipFlop>(Wire_ptr{}, Wire_ptr{}, Wire_ptr{},
1153 Wire_ptr{}, Wire_ptr{}, Wire_ptr{});
1154 flipFlop->setProperty("propagationDelay", 0);
1155 flipFlop->clearWires();
1156 flipFlop->setInput(std::to_underlying(DFlipFlop::Inputs::D), Bus{d}, true);
1157 flipFlop->setInput(std::to_underlying(DFlipFlop::Inputs::Clock), Bus{clock}, true);
1158 flipFlop->setOutput(0, Bus{q});
1159 flipFlop->setOutput(1, Bus{notQ});
1160
1161 auto circuit = std::make_shared<Circuit>(Component_set{flipFlop});
1162 Simulator simulator(circuit);
1163
1164 EXPECT_EQ(simulator.setBus(Bus{clock}, valueFor(Bus{clock}, 1)),
1166 EXPECT_EQ(q->getCurrentState(), State::HIGH);
1167 EXPECT_EQ(notQ->getCurrentState(), State::LOW);
1168}
1169
1170TEST(FlipFlopTest, UnknownDataCapturesAsUnknown)
1171{
1172 auto d = std::make_shared<Wire>(State::UNKNOWN);
1173 auto clock = std::make_shared<Wire>(State::LOW);
1174 auto clear = std::make_shared<Wire>(State::LOW);
1175 auto preset = std::make_shared<Wire>(State::LOW);
1176 auto q = std::make_shared<Wire>(State::LOW);
1177 auto notQ = std::make_shared<Wire>(State::HIGH);
1178
1179 auto flipFlop = std::make_shared<DFlipFlop>(d, clock, clear, preset, q, notQ);
1180 flipFlop->setProperty("propagationDelay", 0);
1181
1182 auto circuit = std::make_shared<Circuit>(Component_set{flipFlop});
1183 Simulator simulator(circuit);
1184
1185 EXPECT_EQ(simulator.setBus(Bus{clock}, valueFor(Bus{clock}, 1)),
1187 EXPECT_EQ(q->getCurrentState(), State::UNKNOWN);
1188 EXPECT_EQ(notQ->getCurrentState(), State::UNKNOWN);
1189}
1190
1191TEST(FlipFlopTest, ZeroPropagationDelayUpdatesImmediately)
1192{
1193 auto d = std::make_shared<Wire>(State::HIGH);
1194 auto clock = std::make_shared<Wire>(State::LOW);
1195 auto clear = std::make_shared<Wire>(State::LOW);
1196 auto preset = std::make_shared<Wire>(State::LOW);
1197 auto q = std::make_shared<Wire>(State::UNKNOWN);
1198 auto notQ = std::make_shared<Wire>(State::UNKNOWN);
1199
1200 auto flipFlop = std::make_shared<DFlipFlop>(d, clock, clear, preset, q, notQ);
1201 flipFlop->setProperty("propagationDelay", 0);
1202
1203 auto circuit = std::make_shared<Circuit>(Component_set{flipFlop});
1204 Simulator simulator(circuit);
1205
1206 EXPECT_EQ(simulator.setBus(Bus{clock}, valueFor(Bus{clock}, 1)),
1208 EXPECT_EQ(q->getCurrentState(), State::HIGH);
1209 EXPECT_EQ(notQ->getCurrentState(), State::LOW);
1210}
1211
1212TEST(FlipFlopTest, ZeroDelayChainCapturesFromPreEdgeSnapshot)
1213{
1214 auto d = std::make_shared<Wire>(State::LOW);
1215 auto clock = std::make_shared<Wire>(State::LOW);
1216 auto clear = std::make_shared<Wire>(State::LOW);
1217 auto preset = std::make_shared<Wire>(State::LOW);
1218
1219 auto q0 = std::make_shared<Wire>(State::UNKNOWN);
1220 auto notQ0 = std::make_shared<Wire>(State::UNKNOWN);
1221 auto q1 = std::make_shared<Wire>(State::UNKNOWN);
1222 auto notQ1 = std::make_shared<Wire>(State::UNKNOWN);
1223 auto q2 = std::make_shared<Wire>(State::UNKNOWN);
1224 auto notQ2 = std::make_shared<Wire>(State::UNKNOWN);
1225
1226 auto ff0 = std::make_shared<DFlipFlop>(d, clock, clear, preset, q0, notQ0);
1227 auto ff1 = std::make_shared<DFlipFlop>(q0, clock, clear, preset, q1, notQ1);
1228 auto ff2 = std::make_shared<DFlipFlop>(q1, clock, clear, preset, q2, notQ2);
1229 for (const auto& flipFlop : {ff0, ff1, ff2})
1230 flipFlop->setProperty("propagationDelay", 0);
1231
1232 auto circuit = std::make_shared<Circuit>(Component_set{ff0, ff1, ff2});
1233 Simulator simulator(circuit);
1234
1235 EXPECT_EQ(simulator.setBus(Bus{clear}, valueFor(Bus{clear}, 1)),
1237 EXPECT_EQ(simulator.setBus(Bus{clear}, valueFor(Bus{clear}, 0)),
1239 EXPECT_EQ(q0->getCurrentState(), State::LOW);
1240 EXPECT_EQ(q1->getCurrentState(), State::LOW);
1241 EXPECT_EQ(q2->getCurrentState(), State::LOW);
1242
1243 EXPECT_EQ(simulator.setBus(Bus{d}, valueFor(Bus{d}, 1)),
1245 EXPECT_EQ(simulator.setBus(Bus{clock}, valueFor(Bus{clock}, 1)),
1247
1248 EXPECT_EQ(q0->getCurrentState(), State::HIGH);
1249 EXPECT_EQ(q1->getCurrentState(), State::LOW);
1250 EXPECT_EQ(q2->getCurrentState(), State::LOW);
1251
1252 EXPECT_EQ(simulator.setBus(Bus{clock}, valueFor(Bus{clock}, 0)),
1254 EXPECT_EQ(simulator.setBus(Bus{clock}, valueFor(Bus{clock}, 1)),
1256
1257 EXPECT_EQ(q0->getCurrentState(), State::HIGH);
1258 EXPECT_EQ(q1->getCurrentState(), State::HIGH);
1259 EXPECT_EQ(q2->getCurrentState(), State::LOW);
1260}
1261
1262TEST(FlipFlopTest, ZeroDelayChainSamplesPreEdgeCombinationalValue)
1263{
1264 auto d = std::make_shared<Wire>(State::LOW);
1265 auto clock = std::make_shared<Wire>(State::LOW);
1266 auto clear = std::make_shared<Wire>(State::LOW);
1267 auto preset = std::make_shared<Wire>(State::LOW);
1268
1269 auto q0 = std::make_shared<Wire>(State::UNKNOWN);
1270 auto notQ0 = std::make_shared<Wire>(State::UNKNOWN);
1271 auto invQ0 = std::make_shared<Wire>(State::UNKNOWN);
1272 auto q1 = std::make_shared<Wire>(State::UNKNOWN);
1273 auto notQ1 = std::make_shared<Wire>(State::UNKNOWN);
1274
1275 auto ff0 = std::make_shared<DFlipFlop>(d, clock, clear, preset, q0, notQ0);
1276 auto inverter = std::make_shared<NotGate>(q0, invQ0);
1277 auto ff1 = std::make_shared<DFlipFlop>(invQ0, clock, clear, preset, q1, notQ1);
1278
1279 ff0->setProperty("propagationDelay", 0);
1280 ff1->setProperty("propagationDelay", 0);
1281 inverter->setProperty("delay", 0);
1282
1283 auto circuit = std::make_shared<Circuit>(Component_set{ff0, inverter, ff1});
1284 Simulator simulator(circuit);
1285
1286 EXPECT_EQ(simulator.setBus(Bus{clear}, valueFor(Bus{clear}, 1)),
1288 EXPECT_EQ(simulator.setBus(Bus{clear}, valueFor(Bus{clear}, 0)),
1290 EXPECT_EQ(q0->getCurrentState(), State::LOW);
1291 EXPECT_EQ(invQ0->getCurrentState(), State::HIGH);
1292 EXPECT_EQ(q1->getCurrentState(), State::LOW);
1293
1294 EXPECT_EQ(simulator.setBus(Bus{d}, valueFor(Bus{d}, 1)),
1296 EXPECT_EQ(simulator.setBus(Bus{clock}, valueFor(Bus{clock}, 1)),
1298
1299 EXPECT_EQ(q0->getCurrentState(), State::HIGH);
1300 EXPECT_EQ(invQ0->getCurrentState(), State::LOW);
1301 EXPECT_EQ(q1->getCurrentState(), State::HIGH);
1302}
1303
1304TEST(FlipFlopTest, DefaultPropagationDelayDefersOutputUpdates)
1305{
1306 auto d = std::make_shared<Wire>(State::HIGH);
1307 auto clock = std::make_shared<Wire>(State::LOW);
1308 auto clear = std::make_shared<Wire>(State::LOW);
1309 auto preset = std::make_shared<Wire>(State::LOW);
1310 auto q = std::make_shared<Wire>(State::UNKNOWN);
1311 auto notQ = std::make_shared<Wire>(State::UNKNOWN);
1312
1313 auto flipFlop = std::make_shared<DFlipFlop>(d, clock, clear, preset, q, notQ);
1314 EXPECT_EQ(flipFlop->getPropertyValue<int>("propagationDelay").value_or(-1), 5);
1315
1316 auto circuit = std::make_shared<Circuit>(Component_set{flipFlop});
1317 Simulator simulator(circuit);
1318
1319 EXPECT_EQ(simulator.setBus(Bus{clock}, valueFor(Bus{clock}, 1)),
1321 EXPECT_EQ(q->getCurrentState(), State::UNKNOWN);
1322 EXPECT_EQ(notQ->getCurrentState(), State::UNKNOWN);
1323
1324 EXPECT_EQ(simulator.run(4), Simulator::RunResult::Completed);
1325 EXPECT_EQ(q->getCurrentState(), State::UNKNOWN);
1326 EXPECT_EQ(notQ->getCurrentState(), State::UNKNOWN);
1327
1328 EXPECT_EQ(simulator.run(1), Simulator::RunResult::Completed);
1329 EXPECT_EQ(q->getCurrentState(), State::HIGH);
1330 EXPECT_EQ(notQ->getCurrentState(), State::LOW);
1331}
1332
1333TEST(FlipFlopTest, SetupViolationCapturesUnknown)
1334{
1335 auto d = std::make_shared<Wire>(State::LOW);
1336 auto clock = std::make_shared<Wire>(State::LOW);
1337 auto clear = std::make_shared<Wire>(State::LOW);
1338 auto preset = std::make_shared<Wire>(State::LOW);
1339 auto q = std::make_shared<Wire>(State::UNKNOWN);
1340 auto notQ = std::make_shared<Wire>(State::UNKNOWN);
1341
1342 auto flipFlop = std::make_shared<DFlipFlop>(d, clock, clear, preset, q, notQ);
1343 flipFlop->setProperty("propagationDelay", 0);
1344 flipFlop->setProperty("setupTime", 3);
1345
1346 auto circuit = std::make_shared<Circuit>(Component_set{flipFlop});
1347 Simulator simulator(circuit);
1348
1349 EXPECT_EQ(simulator.setBus(Bus{clock}, valueFor(Bus{clock}, 1)),
1351 EXPECT_EQ(q->getCurrentState(), State::LOW);
1352
1353 EXPECT_EQ(simulator.setBus(Bus{clock}, valueFor(Bus{clock}, 0)),
1355 EXPECT_EQ(simulator.run(10), Simulator::RunResult::Completed);
1356 EXPECT_EQ(simulator.setBus(Bus{d}, valueFor(Bus{d}, 1)),
1358 EXPECT_EQ(simulator.run(2), Simulator::RunResult::Completed);
1359 EXPECT_EQ(simulator.setBus(Bus{clock}, valueFor(Bus{clock}, 1)),
1361
1362 EXPECT_EQ(q->getCurrentState(), State::UNKNOWN);
1363 EXPECT_EQ(notQ->getCurrentState(), State::UNKNOWN);
1364}
1365
1366TEST(FlipFlopTest, HoldViolationInvalidatesLatchedState)
1367{
1368 auto d = std::make_shared<Wire>(State::HIGH);
1369 auto clock = std::make_shared<Wire>(State::LOW);
1370 auto clear = std::make_shared<Wire>(State::LOW);
1371 auto preset = std::make_shared<Wire>(State::LOW);
1372 auto q = std::make_shared<Wire>(State::UNKNOWN);
1373 auto notQ = std::make_shared<Wire>(State::UNKNOWN);
1374
1375 auto flipFlop = std::make_shared<DFlipFlop>(d, clock, clear, preset, q, notQ);
1376 flipFlop->setProperty("propagationDelay", 0);
1377 flipFlop->setProperty("holdTime", 3);
1378
1379 auto circuit = std::make_shared<Circuit>(Component_set{flipFlop});
1380 Simulator simulator(circuit);
1381
1382 EXPECT_EQ(simulator.setBus(Bus{clock}, valueFor(Bus{clock}, 1)),
1384 EXPECT_EQ(q->getCurrentState(), State::HIGH);
1385
1386 EXPECT_EQ(simulator.run(2), Simulator::RunResult::Completed);
1387 EXPECT_EQ(simulator.setBus(Bus{d}, valueFor(Bus{d}, 0)),
1389
1390 EXPECT_EQ(q->getCurrentState(), State::UNKNOWN);
1391 EXPECT_EQ(notQ->getCurrentState(), State::UNKNOWN);
1392}
1393
1394TEST(FlipFlopTest, EnabledFlipFlopAppliesSetupTimeToEnable)
1395{
1396 auto d = std::make_shared<Wire>(State::HIGH);
1397 auto enable = std::make_shared<Wire>(State::LOW);
1398 auto clock = std::make_shared<Wire>(State::LOW);
1399 auto clear = std::make_shared<Wire>(State::LOW);
1400 auto preset = std::make_shared<Wire>(State::LOW);
1401 auto q = std::make_shared<Wire>(State::UNKNOWN);
1402 auto notQ = std::make_shared<Wire>(State::UNKNOWN);
1403
1404 auto flipFlop = std::make_shared<EFlipFlop>(d, enable, clock, clear, preset, q, notQ);
1405 flipFlop->setProperty("propagationDelay", 0);
1406 flipFlop->setProperty("setupTime", 4);
1407
1408 auto circuit = std::make_shared<Circuit>(Component_set{flipFlop});
1409 Simulator simulator(circuit);
1410
1411 EXPECT_EQ(simulator.setBus(Bus{clear}, valueFor(Bus{clear}, 1)),
1413 EXPECT_EQ(simulator.setBus(Bus{clear}, valueFor(Bus{clear}, 0)),
1415 EXPECT_EQ(q->getCurrentState(), State::LOW);
1416
1417 EXPECT_EQ(simulator.run(10), Simulator::RunResult::Completed);
1418 EXPECT_EQ(simulator.setBus(Bus{enable}, valueFor(Bus{enable}, 1)),
1420 EXPECT_EQ(simulator.run(3), Simulator::RunResult::Completed);
1421 EXPECT_EQ(simulator.setBus(Bus{clock}, valueFor(Bus{clock}, 1)),
1423
1424 EXPECT_EQ(q->getCurrentState(), State::UNKNOWN);
1425 EXPECT_EQ(notQ->getCurrentState(), State::UNKNOWN);
1426}
1427
1428TEST(FlipFlopTest, JKFlipFlopAppliesHoldTimeToInputs)
1429{
1430 auto j = std::make_shared<Wire>(State::HIGH);
1431 auto k = std::make_shared<Wire>(State::LOW);
1432 auto clock = std::make_shared<Wire>(State::LOW);
1433 auto clear = std::make_shared<Wire>(State::LOW);
1434 auto preset = std::make_shared<Wire>(State::LOW);
1435 auto q = std::make_shared<Wire>(State::UNKNOWN);
1436 auto notQ = std::make_shared<Wire>(State::UNKNOWN);
1437
1438 auto flipFlop = std::make_shared<JKFlipFlop>(j, k, clock, clear, preset, q, notQ);
1439 flipFlop->setProperty("propagationDelay", 0);
1440 flipFlop->setProperty("holdTime", 5);
1441
1442 auto circuit = std::make_shared<Circuit>(Component_set{flipFlop});
1443 Simulator simulator(circuit);
1444
1445 EXPECT_EQ(simulator.setBus(Bus{clock}, valueFor(Bus{clock}, 1)),
1447 EXPECT_EQ(q->getCurrentState(), State::HIGH);
1448
1449 EXPECT_EQ(simulator.run(4), Simulator::RunResult::Completed);
1450 EXPECT_EQ(simulator.setBus(Bus{k}, valueFor(Bus{k}, 1)),
1452
1453 EXPECT_EQ(q->getCurrentState(), State::UNKNOWN);
1454 EXPECT_EQ(notQ->getCurrentState(), State::UNKNOWN);
1455}
1456
1457TEST(FlipFlopTest, TimingPropertiesAreValidated)
1458{
1459 auto flipFlop = std::make_shared<DFlipFlop>();
1460
1461 EXPECT_THROW(flipFlop->setProperty("propagationDelay", -1), std::invalid_argument);
1462 EXPECT_THROW(flipFlop->setProperty("setupTime", -1), std::invalid_argument);
1463 EXPECT_THROW(flipFlop->setProperty("holdTime", -1), std::invalid_argument);
1464 EXPECT_THROW(flipFlop->setProperty("triggerEdge", std::string("BOTH")),
1465 std::invalid_argument);
1466}
1467
1468TEST(SimulatorTest, InteractiveSettlingKeepsWaveformChangesAtDistinctTimes)
1469{
1470 auto a = std::make_shared<Wire>(State::LOW);
1471 auto b = std::make_shared<Wire>(State::HIGH);
1472 auto o = std::make_shared<Wire>(State::UNKNOWN);
1473
1474 auto gate = std::make_shared<AndGate>(std::vector<Wire_ptr>{a, b}, o);
1475 gate->setProperty("delay", 0);
1476
1477 auto circuit = std::make_shared<Circuit>(Component_set{gate});
1478 Simulator simulator(circuit);
1479
1480 std::vector<Sample> samples;
1481 auto appendSnapshot = [&samples](uint64_t time, std::vector<BusValue> values) {
1482 if (!samples.empty() && samples.back().time == time) {
1483 samples.back().values = std::move(values);
1484 return;
1485 }
1486 samples.push_back({time, std::move(values)});
1487 };
1488
1489 simulator.setTraceBuses({{"input", Bus{a}}, {"output", Bus{o}}});
1490 simulator.setTraceSink([&](uint64_t time, const std::vector<BusValue>& values) {
1491 appendSnapshot(time, values);
1492 });
1493
1494 auto settleInteractive = [&simulator]() {
1495 const auto result = simulator.runUntilIdle();
1496 if (result != Simulator::RunResult::Completed)
1497 return result;
1498 return simulator.run(1);
1499 };
1500
1501 EXPECT_EQ(settleInteractive(), Simulator::RunResult::Completed);
1502 EXPECT_EQ(simulator.setBus(Bus{a}, valueFor(Bus{a}, 1)),
1504 EXPECT_EQ(settleInteractive(), Simulator::RunResult::Completed);
1505 EXPECT_EQ(simulator.setBus(Bus{a}, valueFor(Bus{a}, 0)),
1507 EXPECT_EQ(settleInteractive(), Simulator::RunResult::Completed);
1508
1509 ASSERT_GE(samples.size(), 4U);
1510 EXPECT_EQ(samples[0].time, 0);
1511 EXPECT_EQ(samples[1].time, 1);
1512 EXPECT_EQ(samples[2].time, 2);
1513 EXPECT_EQ(samples[3].time, 3);
1514 EXPECT_EQ(samples[1].values,
1515 (std::vector<BusValue>{busValueFromBits("1"), busValueFromBits("1")}));
1516 EXPECT_EQ(samples[2].values,
1517 (std::vector<BusValue>{busValueFromBits("0"), busValueFromBits("0")}));
1518}
1519
1520TEST(SimulatorTest, WaveformAppliesSameTimestampInputsTogether)
1521{
1522 auto a = std::make_shared<Wire>(State::LOW);
1523 auto b = std::make_shared<Wire>(State::LOW);
1524 auto o = std::make_shared<Wire>(State::LOW);
1525
1526 auto gate = std::make_shared<XorGate>(std::array<Wire_ptr, 2>{a, b}, o);
1527 gate->setProperty("delay", 0);
1528
1529 auto circuit = std::make_shared<Circuit>(Component_set{gate});
1530 Simulator simulator(circuit);
1531
1532 std::vector<BusValue> tracedValues;
1533 simulator.setTraceBuses({{"xor", Bus{o}}});
1534 simulator.setTraceSink([&](uint64_t, const std::vector<BusValue>& values) {
1535 if (!values.empty())
1536 tracedValues.push_back(values[0]);
1537 });
1538 tracedValues.clear();
1539
1540 const std::vector<Sample> inputSnapshots{
1541 {0, {busValueFromBits("0"), busValueFromBits("0")}},
1542 {3, {busValueFromBits("1"), busValueFromBits("1")}},
1543 };
1544 const std::vector<Simulator::WaveformInputDriver> inputDrivers{
1545 {Bus{a}, {}},
1546 {Bus{b}, {}},
1547 };
1548
1549 EXPECT_EQ(simulator.simulateWaveform(5, inputSnapshots, inputDrivers),
1551 EXPECT_EQ(o->getCurrentState(), State::LOW);
1552 EXPECT_TRUE(std::ranges::none_of(tracedValues, [](const BusValue& value) {
1553 return value == busValueFromBits("1");
1554 }));
1555}
1556
1557TEST(LogicTest, Nand)
1558{
1559 auto a = std::make_shared<Wire>(State::HIGH);
1560 auto b = std::make_shared<Wire>(State::HIGH);
1561 auto o = std::make_shared<Wire>();
1562
1563 auto g = std::make_shared<NandGate>(std::vector<Wire_ptr>{a, b}, o);
1564 auto circ = std::make_shared<Circuit>(Component_set{g});
1565 Simulator sim(circ);
1566 sim.run(20);
1567
1568 EXPECT_EQ(o->getCurrentState(), State::LOW);
1569
1570 sim.setBus(Bus{b}, valueFor(Bus{b}, 0));
1571 sim.run(20);
1572 EXPECT_EQ(o->getCurrentState(), State::HIGH);
1573}
1574
1575TEST(LogicTest, Or)
1576{
1577 auto a = std::make_shared<Wire>(State::ERROR);
1578 auto b = std::make_shared<Wire>(State::ERROR);
1579 auto o = std::make_shared<Wire>();
1580
1581 auto g = std::make_shared<OrGate>(std::vector<Wire_ptr>{a, b}, o);
1582 auto circ = std::make_shared<Circuit>(Component_set{g});
1583 Simulator sim(circ);
1584 sim.run(20);
1585
1586 EXPECT_EQ(o->getCurrentState(), State::ERROR)
1587 << "OR(ERROR, ERROR) = " << to_str(o->getCurrentState());
1588
1589 b->forceSetCurrentState(State::HIGH);
1590 sim.simulateBus(Bus{o});
1591 sim.run(20);
1592 EXPECT_EQ(o->getCurrentState(), State::ERROR)
1593 << "OR(ERROR, HIGH) = " << to_str(o->getCurrentState());
1594
1595 b->forceSetCurrentState(State::LOW);
1596 sim.simulateBus(Bus{o});
1597 sim.run(20);
1598 EXPECT_EQ(o->getCurrentState(), State::ERROR)
1599 << "OR(ERROR, LOW) = " << to_str(o->getCurrentState());
1600
1601 sim.setBus(Bus{a}, valueFor(Bus{a}, 0));
1602 sim.setBus(Bus{b}, valueFor(Bus{b}, 0));
1603 sim.run(20);
1604 EXPECT_EQ(o->getCurrentState(), State::LOW)
1605 << "OR(LOW, LOW) = " << to_str(o->getCurrentState());
1606
1607 sim.setBus(Bus{a}, valueFor(Bus{a}, 1));
1608 sim.run(20);
1609 EXPECT_EQ(o->getCurrentState(), State::HIGH)
1610 << "OR(HIGH, LOW) = " << to_str(o->getCurrentState());
1611
1612 sim.setBus(Bus{b}, valueFor(Bus{b}, 1));
1613 sim.run(20);
1614 EXPECT_EQ(o->getCurrentState(), State::HIGH)
1615 << "OR(HIGH, HIGH) = " << to_str(o->getCurrentState());
1616}
1617
1618TEST(LogicTest, Nor)
1619{
1620 auto a = std::make_shared<Wire>(State::LOW);
1621 auto b = std::make_shared<Wire>(State::LOW);
1622 auto o = std::make_shared<Wire>();
1623
1624 auto g = std::make_shared<NorGate>(std::vector<Wire_ptr>{a, b}, o);
1625 auto circ = std::make_shared<Circuit>(Component_set{g});
1626 Simulator sim(circ);
1627 sim.run(20);
1628
1629 EXPECT_EQ(o->getCurrentState(), State::HIGH);
1630
1631 sim.setBus(Bus{a}, valueFor(Bus{a}, 1));
1632 sim.run(20);
1633 EXPECT_EQ(o->getCurrentState(), State::LOW);
1634}
1635
1636TEST(LogicTest, Xor)
1637{
1638 auto a = std::make_shared<Wire>(State::ERROR);
1639 auto b = std::make_shared<Wire>(State::ERROR);
1640 auto o = std::make_shared<Wire>();
1641
1642 auto g = std::make_shared<XorGate>(std::array<Wire_ptr, 2>{a, b}, o);
1643 auto circ = std::make_shared<Circuit>(Component_set{g});
1644 Simulator sim(circ);
1645 sim.run(20);
1646
1647 EXPECT_EQ(o->getCurrentState(), State::ERROR)
1648 << "XOR(ERROR, ERROR) = " << to_str(o->getCurrentState());
1649
1650 b->forceSetCurrentState(State::HIGH);
1651 sim.simulateBus(Bus{o});
1652 sim.run(20);
1653 EXPECT_EQ(o->getCurrentState(), State::ERROR)
1654 << "XOR(ERROR, HIGH) = " << to_str(o->getCurrentState());
1655
1656 b->forceSetCurrentState(State::LOW);
1657 sim.simulateBus(Bus{o});
1658 sim.run(20);
1659 EXPECT_EQ(o->getCurrentState(), State::ERROR)
1660 << "XOR(ERROR, LOW) = " << to_str(o->getCurrentState());
1661
1662 sim.setBus(Bus{a}, valueFor(Bus{a}, 0));
1663 sim.setBus(Bus{b}, valueFor(Bus{b}, 0));
1664 sim.run(20);
1665 EXPECT_EQ(o->getCurrentState(), State::LOW)
1666 << "XOR(LOW, LOW) = " << to_str(o->getCurrentState());
1667
1668 sim.setBus(Bus{a}, valueFor(Bus{a}, 1));
1669 sim.run(20);
1670 EXPECT_EQ(o->getCurrentState(), State::HIGH)
1671 << "XOR(HIGH, LOW) = " << to_str(o->getCurrentState());
1672
1673 sim.setBus(Bus{b}, valueFor(Bus{b}, 1));
1674 sim.run(20);
1675 EXPECT_EQ(o->getCurrentState(), State::LOW)
1676 << "XOR(HIGH, HIGH) = " << to_str(o->getCurrentState());
1677}
1678
1679TEST(LogicTest, CircuitEditing1)
1680{
1681 auto a = std::make_shared<Wire>(State::HIGH);
1682 auto b = std::make_shared<Wire>(State::LOW);
1683 auto o = std::make_shared<Wire>();
1684
1685 {
1686 auto g = std::make_shared<XorGate>(std::array<Wire_ptr, 2>{a, b}, o);
1687 auto c = std::make_shared<Circuit>(Component_set{g});
1688 Simulator sim(c);
1689 sim.run(20);
1690 EXPECT_EQ(o->getCurrentState(), State::HIGH);
1691 }
1692
1693 {
1694 auto g = std::make_shared<AndGate>(std::vector<Wire_ptr>{a, b}, o);
1695 auto c = std::make_shared<Circuit>(Component_set{g});
1696 Simulator sim(c);
1697 sim.run(20);
1698 EXPECT_EQ(o->getCurrentState(), State::LOW);
1699 }
1700
1701 {
1702 b->forceSetCurrentState(State::HIGH);
1703 auto g = std::make_shared<OrGate>(std::vector<Wire_ptr>{a, b}, o);
1704 auto c = std::make_shared<Circuit>(Component_set{g});
1705 Simulator sim(c);
1706 sim.run(20);
1707 EXPECT_EQ(o->getCurrentState(), State::HIGH);
1708 }
1709}
1710
1711TEST(LogicTest, CircuitEditing2)
1712{
1713 auto a = std::make_shared<Wire>(State::HIGH);
1714 auto b = std::make_shared<Wire>(State::HIGH);
1715 auto c = std::make_shared<Wire>(State::HIGH);
1716
1717 auto o = std::make_shared<Wire>();
1718
1719 auto ag = std::make_shared<AndGate>(std::vector<Wire_ptr>{a, b}, o);
1720 auto circ = std::make_shared<Circuit>(Component_set{ag});
1721 Simulator sim(circ);
1722 sim.run(20);
1723
1724 std::vector<Bus> newInputs = {{c}, {b}};
1725 ag->setInputs(newInputs);
1726
1727 // Dynamic topology alters require instantiating a fresh graph configuration
1728 auto circ2 = std::make_shared<Circuit>(Component_set{ag});
1729 Simulator sim2(circ2);
1730 sim2.run(20);
1731
1732 a->forceSetCurrentState(State::ERROR); // Should not influence the gate anymore
1733
1734 EXPECT_EQ(o->getCurrentState(), State::HIGH);
1735
1736 sim2.setBus(Bus{c}, valueFor(Bus{c}, 0));
1737 sim2.run(20);
1738 EXPECT_EQ(o->getCurrentState(), State::LOW);
1739}
1740
1741TEST(LogicTest, TopologyEditUsesNewSimulator)
1742{
1743 auto a = std::make_shared<Wire>(State::HIGH);
1744 auto b = std::make_shared<Wire>(State::HIGH);
1745 auto c = std::make_shared<Wire>(State::HIGH);
1746 auto o = std::make_shared<Wire>(State::UNKNOWN);
1747
1748 auto gate = std::make_shared<AndGate>(std::vector<Wire_ptr>{a, b}, o);
1749 gate->setProperty("delay", 0);
1750
1751 {
1752 auto circuit = std::make_shared<Circuit>(Component_set{gate});
1753 Simulator simulator(circuit);
1754
1755 EXPECT_EQ(simulator.runUntilIdle(), Simulator::RunResult::Completed);
1756 EXPECT_EQ(o->getCurrentState(), State::HIGH);
1757 }
1758
1759 std::vector<Bus> newInputs = {{c}, {b}};
1760 gate->setInputs(newInputs);
1761
1762 auto circuit = std::make_shared<Circuit>(Component_set{gate});
1763 Simulator simulator(circuit);
1764
1765 a->forceSetCurrentState(State::LOW);
1766 EXPECT_EQ(simulator.setBus(Bus{c}, valueFor(Bus{c}, 0)),
1768 EXPECT_EQ(o->getCurrentState(), State::LOW);
1769}
1770
1771TEST(LogicTest, BusSettingReading)
1772{
1773 auto a = Bus(4);
1774 for (int i = 0; i <= 0b1111; i++) {
1775 (void)a.forceSetCurrentValue(valueFor(a, static_cast<std::uint64_t>(i)));
1776 EXPECT_EQ(a.getCurrentValue(), valueFor(a, static_cast<std::uint64_t>(i)));
1777 }
1778}
1779
1780TEST(LogicTest, BusSettingReadingAtUnsignedIntWidth)
1781{
1782 Bus bus(std::numeric_limits<unsigned int>::digits);
1783
1784 EXPECT_FALSE(
1785 bus.forceSetCurrentValue(valueFor(bus, std::numeric_limits<unsigned int>::max())));
1786 EXPECT_EQ(bus.getCurrentValue(),
1787 valueFor(bus, std::numeric_limits<unsigned int>::max()));
1788
1789 EXPECT_FALSE(bus.setCurrentValue(valueFor(bus, 0), {}));
1790 EXPECT_EQ(bus.getCurrentValue(), valueFor(bus, 0));
1791}
1792
1793TEST(LogicTest, BusAssignmentsNormalizeWidthAndReportMeaningfulOverflow)
1794{
1795 Bus bus(4);
1796
1797 EXPECT_FALSE(bus.forceSetCurrentValue(BusValue{State::HIGH}));
1798 EXPECT_EQ(bus.getCurrentValue(), busValueFromBits("0001"));
1799
1800 EXPECT_FALSE(bus.forceSetCurrentValue(busValueFromBits("000001")));
1801 EXPECT_EQ(bus.getCurrentValue(), busValueFromBits("0001"));
1802
1803 EXPECT_TRUE(bus.forceSetCurrentValue(busValueFromBits("100001")));
1804 EXPECT_EQ(bus.getCurrentValue(), busValueFromBits("0001"));
1805
1806 EXPECT_TRUE(bus.forceSetCurrentValue(busValueFromBits("X00001")));
1807 EXPECT_EQ(bus.getCurrentValue(), busValueFromBits("0001"));
1808}
1809
1810TEST(LogicTest, DisconnectedBusStateQueriesDoNotDereferenceNullWires)
1811{
1812 Bus bus{Wire_ptr{}};
1813
1814 EXPECT_TRUE(bus.isInErrorState());
1815 EXPECT_FALSE(bus.hasUnknowns());
1816 EXPECT_EQ(formatValue(bus.getCurrentValue(), BusValueFormat::Raw), "E");
1817
1818 bus.setSize(2);
1819 EXPECT_TRUE(bus.isInErrorState());
1820 EXPECT_TRUE(bus.hasUnknowns());
1821 EXPECT_EQ(formatValue(bus.getCurrentValue(), BusValueFormat::Raw), "XE");
1822}
1823
1824TEST(LogicTest, GateBitwiseDefaultsAndValidation)
1825{
1826 auto a = std::make_shared<Wire>();
1827 auto b = std::make_shared<Wire>();
1828 auto o = std::make_shared<Wire>();
1829
1830 auto gate = std::make_shared<AndGate>(std::vector<Wire_ptr>{a, b}, o);
1831
1832 EXPECT_EQ(gate->getPropertyValue<bool>("bitwise"), false);
1833 EXPECT_EQ(gate->getPropertyValue<int>("size"), 1);
1834 EXPECT_EQ(gate->getInputs()[0].size(), 1);
1835 EXPECT_EQ(gate->getInputs()[1].size(), 1);
1836 EXPECT_EQ(gate->getOutputs()[0].size(), 1);
1837
1838 EXPECT_THROW(gate->setProperty("size", 0), std::invalid_argument);
1839 EXPECT_THROW(gate->setProperty("size", -2), std::invalid_argument);
1840
1841 auto notGate = std::make_shared<NotGate>(a, o);
1842 EXPECT_FALSE(notGate->getProperty("bitwise").has_value());
1843 EXPECT_EQ(notGate->getPropertyValue<int>("size"), 1);
1844 EXPECT_THROW(notGate->setProperty("size", 0), std::invalid_argument);
1845 EXPECT_THROW(notGate->setProperty("size", -2), std::invalid_argument);
1846
1847 notGate->setProperty("size", 4);
1848 EXPECT_EQ(notGate->inputBuses()[0].size(), 4);
1849 EXPECT_EQ(notGate->outputBuses()[0].size(), 4);
1850}
1851
1852TEST(LogicTest, GateBitwiseReshapesIO)
1853{
1854 auto gate = std::make_shared<OrGate>(
1855 std::vector<Wire_ptr>{std::make_shared<Wire>(), std::make_shared<Wire>()},
1856 std::make_shared<Wire>());
1857
1858 gate->setProperty("size", 4);
1859 ASSERT_EQ(gate->inputBuses().size(), 1);
1860 EXPECT_EQ(gate->inputBuses()[0].size(), 4);
1861 EXPECT_EQ(gate->outputBuses()[0].size(), 1);
1862
1863 gate->setProperty("bitwise", true);
1864 ASSERT_EQ(gate->inputBuses().size(), 2);
1865 EXPECT_EQ(gate->inputBuses()[0].size(), 4);
1866 EXPECT_EQ(gate->inputBuses()[1].size(), 4);
1867 EXPECT_EQ(gate->outputBuses()[0].size(), 4);
1868
1869 gate->setProperty("size", 2);
1870 EXPECT_EQ(gate->inputBuses()[0].size(), 2);
1871 EXPECT_EQ(gate->inputBuses()[1].size(), 2);
1872 EXPECT_EQ(gate->outputBuses()[0].size(), 2);
1873
1874 gate->setProperty("bitwise", false);
1875 ASSERT_EQ(gate->inputBuses().size(), 1);
1876 EXPECT_EQ(gate->inputBuses()[0].size(), 2);
1877 EXPECT_EQ(gate->outputBuses()[0].size(), 1);
1878
1879 gate->setProperty("size", 1);
1880 ASSERT_EQ(gate->inputBuses().size(), 2);
1881 EXPECT_EQ(gate->inputBuses()[0].size(), 1);
1882 EXPECT_EQ(gate->inputBuses()[1].size(), 1);
1883 EXPECT_EQ(gate->outputBuses()[0].size(), 1);
1884}
1885
1886TEST(LogicTest, ReductionGatesMatchSeparateScalarInputs)
1887{
1888 const std::vector<std::function<std::shared_ptr<Gate>()>> factories{
1889 [] { return std::make_shared<AndGate>(); },
1890 [] { return std::make_shared<OrGate>(); },
1891 [] { return std::make_shared<NandGate>(); },
1892 [] { return std::make_shared<NorGate>(); },
1893 [] { return std::make_shared<XorGate>(); },
1894 };
1895 // Exhaust all four-state combinations, including unknown and error bits.
1897 for (const auto& makeGate : factories) {
1898 for (unsigned pattern = 0; pattern < 64; ++pattern) {
1899 auto reduction = makeGate();
1900 reduction->setInputs({Bus(1), Bus(1)});
1901 reduction->setOutputs({Bus(1)});
1902 reduction->setProperty("size", 3);
1903 auto scalar = makeGate();
1904 scalar->setInputs({Bus(1), Bus(1), Bus(1)});
1905 scalar->setOutputs({Bus(1)});
1906 for (unsigned bit = 0; bit < 3; ++bit) {
1907 const auto state = states[(pattern >> (2 * bit)) & 3];
1908 reduction->inputBuses()[0][bit]->forceSetCurrentState(state);
1909 scalar->inputBuses()[bit][0]->forceSetCurrentState(state);
1910 }
1911 auto circuit = std::make_shared<Circuit>(Component_set{reduction, scalar}, false);
1912 Simulator sim(circuit);
1913 ASSERT_EQ(sim.runUntilIdle(), Simulator::RunResult::Completed);
1914 EXPECT_EQ(reduction->outputBuses()[0][0]->getCurrentState(),
1915 scalar->outputBuses()[0][0]->getCurrentState())
1916 << reduction->typeName() << " pattern " << pattern;
1917 }
1918 }
1919}
1920
1921TEST(LogicTest, AndBitwiseSimulation)
1922{
1923 auto gate = std::make_shared<AndGate>(
1924 std::vector<Wire_ptr>{std::make_shared<Wire>(), std::make_shared<Wire>()},
1925 std::make_shared<Wire>());
1926 gate->setProperty("size", 4);
1927 gate->setProperty("bitwise", true);
1928
1929 auto circ = std::make_shared<Circuit>(Component_set{gate});
1930 Simulator sim(circ);
1931 sim.setBus(gate->getInputs()[0], valueFor(gate->getInputs()[0], 0b1101));
1932 sim.setBus(gate->getInputs()[1], valueFor(gate->getInputs()[1], 0b1011));
1933 sim.run(20);
1934
1935 expectBusStates(gate->getOutputs()[0],
1936 {State::HIGH, State::LOW, State::LOW, State::HIGH});
1937}
1938
1939TEST(LogicTest, OrBitwiseSimulation)
1940{
1941 auto gate = std::make_shared<OrGate>(
1942 std::vector<Wire_ptr>{std::make_shared<Wire>(), std::make_shared<Wire>()},
1943 std::make_shared<Wire>());
1944 gate->setProperty("size", 4);
1945 gate->setProperty("bitwise", true);
1946
1947 auto circ = std::make_shared<Circuit>(Component_set{gate});
1948 Simulator sim(circ);
1949 sim.setBus(gate->getInputs()[0], valueFor(gate->getInputs()[0], 0b0101));
1950 sim.setBus(gate->getInputs()[1], valueFor(gate->getInputs()[1], 0b1010));
1951 sim.run(20);
1952
1953 expectBusStates(gate->getOutputs()[0],
1954 {State::HIGH, State::HIGH, State::HIGH, State::HIGH});
1955}
1956
1957TEST(LogicTest, NandBitwiseSimulation)
1958{
1959 auto gate = std::make_shared<NandGate>(
1960 std::vector<Wire_ptr>{std::make_shared<Wire>(), std::make_shared<Wire>()},
1961 std::make_shared<Wire>());
1962 gate->setProperty("size", 4);
1963 gate->setProperty("bitwise", true);
1964
1965 auto circ = std::make_shared<Circuit>(Component_set{gate});
1966 Simulator sim(circ);
1967 sim.setBus(gate->getInputs()[0], valueFor(gate->getInputs()[0], 0b1101));
1968 sim.setBus(gate->getInputs()[1], valueFor(gate->getInputs()[1], 0b1011));
1969 sim.run(20);
1970
1971 expectBusStates(gate->getOutputs()[0],
1972 {State::LOW, State::HIGH, State::HIGH, State::LOW});
1973}
1974
1975TEST(LogicTest, NorBitwiseSimulation)
1976{
1977 auto gate = std::make_shared<NorGate>(
1978 std::vector<Wire_ptr>{std::make_shared<Wire>(), std::make_shared<Wire>()},
1979 std::make_shared<Wire>());
1980 gate->setProperty("size", 4);
1981 gate->setProperty("bitwise", true);
1982
1983 auto circ = std::make_shared<Circuit>(Component_set{gate});
1984 Simulator sim(circ);
1985 sim.setBus(gate->getInputs()[0], valueFor(gate->getInputs()[0], 0b0101));
1986 sim.setBus(gate->getInputs()[1], valueFor(gate->getInputs()[1], 0b1000));
1987 sim.run(20);
1988
1989 expectBusStates(gate->getOutputs()[0],
1990 {State::LOW, State::HIGH, State::LOW, State::LOW});
1991}
1992
1993TEST(LogicTest, XorBitwiseSimulationPreservesUnknownAndErrorPerBit)
1994{
1995 auto gate = std::make_shared<XorGate>(
1996 std::array<Wire_ptr, 2>{std::make_shared<Wire>(), std::make_shared<Wire>()},
1997 std::make_shared<Wire>());
1998 gate->setProperty("size", 4);
1999 gate->setProperty("bitwise", true);
2000
2001 auto inputs = gate->getInputs();
2002 inputs[0][0]->forceSetCurrentState(State::LOW);
2003 inputs[1][0]->forceSetCurrentState(State::HIGH);
2004 inputs[0][1]->forceSetCurrentState(State::HIGH);
2005 inputs[1][1]->forceSetCurrentState(State::HIGH);
2006 inputs[0][2]->forceSetCurrentState(State::UNKNOWN);
2007 inputs[1][2]->forceSetCurrentState(State::LOW);
2008 inputs[0][3]->forceSetCurrentState(State::ERROR);
2009 inputs[1][3]->forceSetCurrentState(State::HIGH);
2010
2011 auto circ = std::make_shared<Circuit>(Component_set{gate});
2012 Simulator sim(circ);
2013 sim.run(20);
2014
2015 expectBusStates(gate->getOutputs()[0],
2016 {State::HIGH, State::LOW, State::UNKNOWN, State::ERROR});
2017}
2018
2019TEST(LogicTest, NotGateSimulatesVectorAndLogicalInputs)
2020{
2021 auto vectorNot =
2022 std::make_shared<NotGate>(std::make_shared<Wire>(), std::make_shared<Wire>());
2023 vectorNot->setProperty("size", 4);
2024 vectorNot->inputBuses()[0][0]->forceSetCurrentState(State::LOW);
2025 vectorNot->inputBuses()[0][1]->forceSetCurrentState(State::HIGH);
2026 vectorNot->inputBuses()[0][2]->forceSetCurrentState(State::UNKNOWN);
2027 vectorNot->inputBuses()[0][3]->forceSetCurrentState(State::ERROR);
2028
2029 auto logicalNot =
2030 std::make_shared<NotGate>(std::make_shared<Wire>(), std::make_shared<Wire>());
2031 logicalNot->setInputs({Bus(3)});
2032 logicalNot->inputBuses()[0][0]->forceSetCurrentState(State::LOW);
2033 logicalNot->inputBuses()[0][1]->forceSetCurrentState(State::LOW);
2034 logicalNot->inputBuses()[0][2]->forceSetCurrentState(State::LOW);
2035
2036 auto unknownLogicalNot =
2037 std::make_shared<NotGate>(std::make_shared<Wire>(), std::make_shared<Wire>());
2038 unknownLogicalNot->setInputs({Bus(2)});
2039 unknownLogicalNot->inputBuses()[0][0]->forceSetCurrentState(State::LOW);
2040 unknownLogicalNot->inputBuses()[0][1]->forceSetCurrentState(State::UNKNOWN);
2041
2042 auto circuit = std::make_shared<Circuit>(
2043 Component_set{vectorNot, logicalNot, unknownLogicalNot}, false);
2044 Simulator simulator(circuit);
2045 ASSERT_EQ(simulator.runUntilIdle(), Simulator::RunResult::Completed);
2046
2047 expectBusStates(vectorNot->outputBuses()[0],
2048 {State::HIGH, State::LOW, State::UNKNOWN, State::ERROR});
2049 expectBusStates(logicalNot->outputBuses()[0], {State::HIGH});
2050 expectBusStates(unknownLogicalNot->outputBuses()[0], {State::UNKNOWN});
2051}
2052
2053// --- Component Property Tests --------------------------------------------------------
2054
2055TEST(ComponentTest, SetAndGetIntProperty)
2056{
2057 struct TestComponent : public Component {
2058 TestComponent() : Component({}, {}) { defineProperty("value", 10); }
2059 std::string_view typeName() const override { return "TestComponent"; }
2060 void simulate(Simulator& sim) override {}
2061 };
2062
2063 auto c = std::make_shared<TestComponent>();
2064
2065 auto prop = c->getProperty("value");
2066 ASSERT_TRUE(prop.has_value());
2067 EXPECT_EQ(std::get<int>(*prop), 10);
2068
2069 c->setProperty("value", 20);
2070 prop = c->getProperty("value");
2071 EXPECT_EQ(std::get<int>(*prop), 20);
2072}
2073
2074TEST(ComponentTest, UnconnectedInputMayDeclareDefaultState)
2075{
2076 DefaultedInputTestComponent component;
2077 EXPECT_EQ(component.unconnectedInputDefault(0), State::HIGH);
2078 EXPECT_EQ(component.readInput(), State::HIGH);
2079
2080 auto low = std::make_shared<Wire>(State::LOW);
2081 component.setInput(0, Bus{low});
2082 EXPECT_EQ(component.readInput(), State::LOW);
2083}
2084
2085TEST(ComponentTest, SetAndGetIntPropertyTemplated)
2086{
2087 struct TestComponent : public Component {
2088 TestComponent() : Component({}, {}) { defineProperty("value", 10); }
2089 std::string_view typeName() const override { return "TestComponent"; }
2090 void simulate(Simulator& sim) override {}
2091 };
2092
2093 auto c = std::make_shared<TestComponent>();
2094
2095 auto prop = c->getPropertyValue<int>("value");
2096 ASSERT_TRUE(prop.has_value());
2097 EXPECT_EQ(*prop, 10);
2098
2099 c->setPropertyValue<int>("value", 20);
2100 prop = c->getPropertyValue<int>("value");
2101 EXPECT_EQ(*prop, 20);
2102}
2103
2104TEST(ComponentTest, SetAndGetBoolProperty)
2105{
2106 struct TestComponent : public Component {
2107 TestComponent() : Component({}, {}) { defineProperty("enabled", false); }
2108 std::string_view typeName() const override { return "TestComponent"; }
2109 void simulate(Simulator& sim) override {}
2110 };
2111
2112 auto c = std::make_shared<TestComponent>();
2113
2114 auto prop = c->getProperty("enabled");
2115 ASSERT_TRUE(prop.has_value());
2116 EXPECT_EQ(std::get<bool>(*prop), false);
2117
2118 c->setProperty("enabled", true);
2119 prop = c->getProperty("enabled");
2120 EXPECT_EQ(std::get<bool>(*prop), true);
2121}
2122
2123TEST(ComponentTest, SetAndGetStringProperty)
2124{
2125 struct TestComponent : public Component {
2126 TestComponent() : Component({}, {})
2127 {
2128 defineProperty("name", std::string("default"));
2129 }
2130 std::string_view typeName() const override { return "TestComponent"; }
2131 void simulate(Simulator& sim) override {}
2132 };
2133
2134 auto c = std::make_shared<TestComponent>();
2135
2136 auto prop = c->getProperty("name");
2137 ASSERT_TRUE(prop.has_value());
2138 EXPECT_EQ(std::get<std::string>(*prop), "default");
2139
2140 c->setProperty("name", std::string("custom"));
2141 prop = c->getProperty("name");
2142 EXPECT_EQ(std::get<std::string>(*prop), "custom");
2143}
2144
2145TEST(ComponentTest, SetAndGetBusValueProperty)
2146{
2147 struct TestComponent : public Component {
2148 TestComponent() : Component({}, {}) { defineProperty("value", BusValue{State::LOW}); }
2149 std::string_view typeName() const override { return "TestComponent"; }
2150 void simulate(Simulator&) override {}
2151 };
2152
2153 auto component = std::make_shared<TestComponent>();
2154 const auto value = busValueFromBits("10X1");
2155 component->setProperty("value", value);
2156 EXPECT_EQ(component->getPropertyValue<BusValue>("value"), value);
2157 EXPECT_THROW(component->setProperty("value", std::string("10X1")),
2158 std::invalid_argument);
2159}
2160
2161TEST(ComponentTest, SetAndGetStringListProperty)
2162{
2163 auto c = std::make_shared<StringListPropertyTestComponent>();
2164
2165 auto prop = c->getPropertyValue<std::string>("orientation");
2166 ASSERT_TRUE(prop.has_value());
2167 EXPECT_EQ(*prop, "DOWN");
2168
2169 const auto options = c->getStringPropertyOptions("orientation");
2170 ASSERT_TRUE(options.has_value());
2171 EXPECT_EQ(options->get().size(), 4);
2172
2173 c->setProperty("orientation", std::string("LEFT"));
2174 EXPECT_EQ(c->getPropertyValue<std::string>("orientation").value(), "LEFT");
2175}
2176
2177TEST(ComponentTest, StringListPropertyRejectsInvalidValues)
2178{
2179 auto c = std::make_shared<StringListPropertyTestComponent>();
2180
2181 EXPECT_THROW(c->setProperty("orientation", std::string("DIAGONAL")),
2182 std::invalid_argument);
2183 EXPECT_EQ(c->getPropertyValue<std::string>("orientation").value(), "DOWN");
2184}
2185
2186TEST(ComponentTest, StringListPropertyRejectsInvalidDefault)
2187{
2188 EXPECT_THROW((void)std::make_shared<StringListPropertyTestComponent>("DIAGONAL"),
2189 std::invalid_argument);
2190}
2191
2192TEST(ComponentTest, StringListPropertyRejectsInvalidCallbackResult)
2193{
2194 auto c = std::make_shared<StringListPropertyTestComponent>();
2195
2196 EXPECT_THROW(
2197 c->setPropertyCallback(
2198 "orientation", [](const PropertyValue&) { return std::string("DIAGONAL"); }),
2199 std::invalid_argument);
2200 EXPECT_EQ(c->getPropertyValue<std::string>("orientation").value(), "DOWN");
2201}
2202
2203TEST(ComponentTest, GetPropertyNotFound)
2204{
2205 struct TestComponent : public Component {
2206 TestComponent() : Component({}, {}) { defineProperty("value", 10); }
2207 std::string_view typeName() const override { return "TestComponent"; }
2208 void simulate(Simulator& sim) override {}
2209 };
2210
2211 auto c = std::make_shared<TestComponent>();
2212
2213 auto prop = c->getProperty("nonexistent");
2214 EXPECT_FALSE(prop.has_value());
2215}
2216
2217TEST(ComponentTest, SetPropertyTypeMismatch)
2218{
2219 struct TestComponent : public Component {
2220 TestComponent() : Component({}, {}) { defineProperty("value", 10); }
2221 std::string_view typeName() const override { return "TestComponent"; }
2222 void simulate(Simulator& sim) override {}
2223 };
2224
2225 auto c = std::make_shared<TestComponent>();
2226
2227 EXPECT_THROW(c->setProperty("value", std::string("wrong type")), std::invalid_argument);
2228}
2229
2230TEST(ComponentTest, SetPropertyUndefined)
2231{
2232 struct TestComponent : public Component {
2233 TestComponent() : Component({}, {}) {}
2234 std::string_view typeName() const override { return "TestComponent"; }
2235 void simulate(Simulator& sim) override {}
2236 };
2237
2238 auto c = std::make_shared<TestComponent>();
2239
2240 EXPECT_THROW(c->setProperty("undefined", 10), std::invalid_argument);
2241}
2242
2243TEST(ComponentTest, GetProperties)
2244{
2245 struct TestComponent : public Component {
2246 TestComponent() : Component({}, {})
2247 {
2248 defineProperty("intVal", 5);
2249 defineProperty("boolVal", true);
2250 defineProperty("strVal", std::string("hello"));
2251 }
2252 std::string_view typeName() const override { return "TestComponent"; }
2253 void simulate(Simulator& sim) override {}
2254 };
2255
2256 auto c = std::make_shared<TestComponent>();
2257 auto props = c->getProperties();
2258
2259 EXPECT_EQ(props.size(), 3);
2260 EXPECT_EQ(std::get<int>(props.at("intVal")), 5);
2261 EXPECT_EQ(std::get<bool>(props.at("boolVal")), true);
2262 EXPECT_EQ(std::get<std::string>(props.at("strVal")), "hello");
2263}
bool setCurrentValue(const BusValue &value, const Component_weakPtr &requestedBy)
Definition wire.cpp:516
bool hasUnknowns() const
Definition wire.cpp:545
bool forceSetCurrentValue(const BusValue &value)
Definition wire.cpp:487
bool isInErrorState() const
Definition wire.cpp:538
void setSize(unsigned short size)
Definition wire.cpp:463
BusValue getCurrentValue() const
Definition wire.cpp:530
Base class for all digital circuit components.
virtual std::string_view typeName() const =0
Gets the component type name.
virtual void simulate(SILICON::simulation::Simulator &sim)
Executes the component's logic.
void defineProperty(std::string key, T &&defaultValue, PropertyCallback callback=nullptr)
Defines a property with a default value and optional callback.
@ Preset
Active-high asynchronous preset.
@ Clear
Active-high asynchronous clear.
@ D
Data input captured on the selected clock edge.
void simulate(SILICON::simulation::Simulator &sim) override
Executes the component's logic.
Definition gates.cpp:232
Executes event-driven simulation of a Circuit.
Definition simulator.hpp:74
static uint64_t getMaxSimulationSteps()
static EdgeType edgeType(const Context &context, const Wire_ptr &wire)
Classifies one wire's transition in a simulation context.
RunResult run(uint64_t duration, CancellationCheck isCancelled={})
Executes the simulation for a specified duration.
static void setMaxSimulationSteps(uint64_t value)
void updateBus(const Bus &bus, const BusValue &value, uint64_t delay, const Component_weakPtr &source)
Updates a bus to a new value through the normal wire-update path.
void updateWire(const Wire_ptr &target, State newState, uint64_t delay, const Component_weakPtr &source)
Updates a wire with a new state and optional delay.
TEST(SimulatorTest, CyclicComponentsReadOneSnapshotPerDeltaCycle)
Definition logic.cpp:135
std::shared_ptr< Wire > Wire_ptr
Definition wire.hpp:116
std::variant< int, bool, std::string, BusValue > PropertyValue
Variant type for component properties.
boost::multiprecision::cpp_int BigInt
std::pair< BusValue, BusValue > divide(const BusValue &a, const BusValue &b, Signedness signedness)
Definition wire.cpp:425
std::set< Component_ptr, std::owner_less< Component_ptr > > Component_set
Definition wire.hpp:54
BusValue twosComplement(const BusValue &n)
Definition wire.cpp:272
BusValue busValueFromBits(const std::string_view bits)
Strictly decodes an MSB-first raw string containing 0, 1, X, or E.
std::string to_str(State s)
Definition wire.cpp:77
BusValue busValueFromInteger(const BigInt &value, const std::size_t width)
Builds an LSB-first BusValue from the low width bits of an integer. Negative values use two's complem...
std::string formatValue(const BusValue &value, const BusValueFormat format, const std::size_t fixedWidth)
Format an LSB-first BusValue for display.
std::vector< State > BusValue
Definition wire.hpp:120
void appendSnapshot(Trace &trace, const uint64_t time, std::vector< core::BusValue > values)
Context describing why a component is being evaluated.
Definition component.hpp:90
bool changed(const core::Wire_ptr &wire) const
Returns true when a wire has a captured previous state different from now.
bool initialEvaluation
True for initial or otherwise full-plan evaluation.
Definition component.hpp:92
std::optional< core::State > previousState(const core::Wire_ptr &wire) const
Returns the state a wire had before this reactive evaluation, if captured.
std::span< const core::Bus > changedBuses
Buses that caused a reactive forward-cone evaluation.
Definition component.hpp:95
BusValue valueFor(const Bus &bus, const std::uint64_t value)
Definition tests.hpp:11