35void expectBusStates(
const Bus& bus, std::initializer_list<State> expected)
37 ASSERT_EQ(bus.
size(), expected.size());
40 for (
const State state : expected) {
41 EXPECT_EQ(bus[index]->getCurrentState(), state) <<
"Bit " << index;
46class StringListPropertyTestComponent :
public Component {
48 explicit StringListPropertyTestComponent(std::string defaultValue =
"DOWN")
51 defineStringListProperty(
"orientation", std::move(defaultValue),
52 {
"UP",
"DOWN",
"LEFT",
"RIGHT"});
55 std::string_view typeName()
const override {
return "StringListPropertyTest"; }
56 void simulate(Simulator& sim)
override {}
59class DefaultedInputTestComponent :
public Component {
63 defineUnconnectedInputDefault(0, State::HIGH);
66 [[nodiscard]]
State readInput()
const {
return inputState(0); }
67 std::string_view typeName()
const override {
return "DefaultedInputTest"; }
68 void simulate(Simulator&)
override {}
71class CountingNotGate :
public NotGate {
75 int simulateCount = 0;
77 void simulate(Simulator& sim)
override
84class ContextRecordingComponent :
public Component {
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;
94 explicit ContextRecordingComponent(Bus input) :
Component({std::move(input)}, {}) {}
96 std::string_view typeName()
const override {
return "ContextRecording"; }
98 void simulate(Simulator&)
override { ++legacyCallCount; }
100 void simulate(Simulator&,
const Context& context)
override
105 for (
const auto& wire : inputs[0]) {
106 record.previousInputStates.push_back(context.
previousState(wire));
107 record.changedInputs.push_back(context.
changed(wire));
110 records.push_back(std::move(record));
113 int legacyCallCount = 0;
114 std::vector<Record> records;
117class DeltaCycleTestComponent :
public Component {
119 using Action = std::function<void(Simulator&, DeltaCycleTestComponent&)>;
121 DeltaCycleTestComponent(std::vector<Bus> inputs, std::vector<Bus> outputs,
123 :
Component(std::move(inputs), std::move(outputs)), action(std::move(action))
127 std::string_view typeName()
const override {
return "DeltaCycleTest"; }
128 void simulate(Simulator& sim)
override { action(sim, *
this); }
135TEST(SimulatorTest, CyclicComponentsReadOneSnapshotPerDeltaCycle)
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());
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());
158 auto circuit = std::make_shared<Circuit>(
Component_set{xDriver, yDriver},
false);
163 ASSERT_EQ(xReads.size(), 3);
164 ASSERT_EQ(yReads.size(), 3);
173TEST(SimulatorTest, IndependentCyclicStepsKeepSeparateStagingBuffers)
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());
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());
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());
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());
203 auto circuit = std::make_shared<Circuit>(
213TEST(SimulatorTest, CancelledCyclicPassDiscardsStagedWrites)
215 auto trigger = std::make_shared<Wire>(
State::LOW);
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) {
228 auto yDriver = std::make_shared<DeltaCycleTestComponent>(
229 std::vector<Bus>{
Bus{x}}, std::vector<Bus>{
Bus{y}},
230 [&](
Simulator& sim, DeltaCycleTestComponent& self) {
237 auto circuit = std::make_shared<Circuit>(
Component_set{xDriver, yDriver},
false);
239 EXPECT_EQ(simulator.setBus(
Bus{trigger},
BusValue{State::HIGH},
240 [&]() { return writes > 0; }),
245 EXPECT_EQ(simulator.setBus(
Bus{trigger},
BusValue{State::LOW}),
248 EXPECT_EQ(simulator.setBus(
Bus{trigger},
BusValue{State::HIGH}),
254TEST(SimulatorTest, CyclicConflictingDriversLeaveWireInError)
259 auto first = std::make_shared<DeltaCycleTestComponent>(
260 std::vector<Bus>{
Bus{y}}, std::vector<Bus>{
Bus{x}},
261 [x](
Simulator& sim, DeltaCycleTestComponent& self) {
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) {
273 auto circuit = std::make_shared<Circuit>(
Component_set{first, second},
false);
280TEST(SimulatorTest, RepeatedCyclicWritesByOneSourceKeepItsLastValue)
285 auto xDriver = std::make_shared<DeltaCycleTestComponent>(
286 std::vector<Bus>{
Bus{y}}, std::vector<Bus>{
Bus{x}},
287 [x](
Simulator& sim, DeltaCycleTestComponent& self) {
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());
297 auto circuit = std::make_shared<Circuit>(
Component_set{xDriver, yDriver},
false);
303TEST(SimulatorTest, PositiveDelayInsideSccUsesEventQueue)
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());
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());
319 auto circuit = std::make_shared<Circuit>(
Component_set{immediate, delayed},
false);
330TEST(ConstantComponentTest, DrivesAndResizesBinaryBusValue)
333 auto constant = std::make_shared<ConstantComponent>(output,
busValueFromBits(
"10X1"));
334 auto circuit = std::make_shared<Circuit>(
Component_set{constant},
false);
340 constant->setProperty(
"size", 6);
341 EXPECT_EQ(constant->outputBuses()[0].size(), 6);
345 EXPECT_THROW(constant->setProperty(
"value",
BusValue{State::ERROR}),
346 std::invalid_argument);
349TEST(DummyBusInputComponentTest, ResizesValuesWithoutIntegerConversion)
351 auto input = std::make_shared<DummyBusInputComponent>(
Bus(4),
"input");
354 EXPECT_EQ(input->outputBuses()[0].getCurrentValue(),
busValueFromBits(
"0001"));
356 input->setProperty(
"size", 70);
358 input->setBusValue(wide);
359 EXPECT_EQ(input->outputBuses()[0].getCurrentValue(), wide);
362TEST(BusValueArithmeticTest, AddsKnownAndFourStateValues)
374TEST(BusValueArithmeticTest, TwosComplementUsesFourStateOperators)
383TEST(BusValueArithmeticTest, DivisionPreservesOperandWidths)
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] =
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");
402TEST(BusValueArithmeticTest, DivisionSupportsArbitraryPrecision)
407 const BigInt dividend = divisor * quotient + remainder;
409 const auto [actualQuotient, actualRemainder] =
415TEST(BusValueArithmeticTest, DivisionPropagatesErrorBeforeUnknown)
417 for (
const auto& [dividend, divisor, state] :
423 const auto [quotient, remainder] =
divide(a, b);
424 EXPECT_EQ(quotient,
BusValue(a.size(), state));
425 EXPECT_EQ(remainder,
BusValue(b.size(), state));
429TEST(BusValueArithmeticTest, DivisionRejectsEmptyOperandsAndZeroDivisors)
432 EXPECT_THROW((
void)(
divide(
BusValue{}, one)), std::invalid_argument);
433 EXPECT_THROW((
void)(
divide(one,
BusValue{})), std::invalid_argument);
437 std::invalid_argument);
439 std::invalid_argument);
446 auto o = std::make_shared<Wire>();
448 auto g = std::make_shared<AndGate>(std::vector<Wire_ptr>{a, b}, o);
454 <<
"AND(ERROR, ERROR) = " <<
to_str(o->getCurrentState());
458 sim.simulateBus(
Bus{o});
461 <<
"AND(ERROR, HIGH) = " <<
to_str(o->getCurrentState());
464 sim.simulateBus(
Bus{o});
467 <<
"AND(ERROR, LOW) = " <<
to_str(o->getCurrentState());
474 <<
"AND(LOW, LOW) = " <<
to_str(o->getCurrentState());
479 <<
"AND(HIGH, LOW) = " <<
to_str(o->getCurrentState());
484 <<
"AND(HIGH, HIGH) = " <<
to_str(o->getCurrentState());
487TEST(SimulatorTest, CancelledRunCanResumePendingEvents)
491 auto o = std::make_shared<Wire>();
493 auto gate = std::make_shared<AndGate>(std::vector<Wire_ptr>{a, b}, o);
494 auto circuit = std::make_shared<Circuit>(
Component_set{gate});
496 const auto stateBeforeCancellation = o->getCurrentState();
499 EXPECT_EQ(o->getCurrentState(), stateBeforeCancellation);
505TEST(SimulatorTest, CancellationStopsBusPropagation)
509 auto o = std::make_shared<Wire>();
511 auto gate = std::make_shared<AndGate>(std::vector<Wire_ptr>{a, b}, o);
512 auto circuit = std::make_shared<Circuit>(
Component_set{gate});
515 EXPECT_EQ(simulator.setBus(
Bus{a},
valueFor(
Bus{a}, 1), []() {
return true; }),
520TEST(SimulatorTest, PassesSimulationContextToComponents)
522 auto lowBit = std::make_shared<Wire>(
State::LOW);
523 auto highBit = std::make_shared<Wire>(
State::LOW);
524 Bus input{lowBit, highBit};
526 auto recorder = std::make_shared<ContextRecordingComponent>(input);
527 auto circuit = std::make_shared<Circuit>(
Component_set{recorder});
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);
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}));
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}));
561TEST(SimulatorTest, DelayedEventBatchCapturesPreviousStateBeforeApplyingEvents)
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);
573 auto recorder = std::make_shared<ContextRecordingComponent>(
Bus{x, y});
574 auto circuit = std::make_shared<Circuit>(
Component_set{xDriver, yDriver, recorder});
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());
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}));
595TEST(SimulatorTest, SimulatesInternalInputWaveform)
599 auto o = std::make_shared<Wire>();
601 auto gate = std::make_shared<AndGate>(std::vector<Wire_ptr>{a, b}, o);
602 auto circuit = std::make_shared<Circuit>(
Component_set{gate});
605 const std::vector<Sample> inputSnapshots{
609 const std::vector<Simulator::WaveformInputDriver> inputDrivers{
614 EXPECT_EQ(simulator.simulateWaveform(10, inputSnapshots, inputDrivers),
616 EXPECT_EQ(simulator.getCurrentTime(), 10);
620TEST(SimulatorTest, WaveformInputSampleCapturesPreviousWireStates)
622 auto lowBit = std::make_shared<Wire>(
State::LOW);
623 auto highBit = std::make_shared<Wire>(
State::LOW);
624 Bus input{lowBit, highBit};
626 auto recorder = std::make_shared<ContextRecordingComponent>(input);
627 auto circuit = std::make_shared<Circuit>(
Component_set{recorder});
631 const std::vector<Simulator::WaveformInputDriver> inputDrivers{{input, {}}};
633 EXPECT_EQ(simulator.simulateWaveform(1, inputSnapshots, inputDrivers),
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}));
650TEST(SimulatorTest, WaveformDoesNotPropagateWhenNormalizedValueIsUnchanged)
653 auto highBit = std::make_shared<Wire>(
State::LOW);
654 Bus input{lowBit, highBit};
656 auto recorder = std::make_shared<ContextRecordingComponent>(input);
657 auto circuit = std::make_shared<Circuit>(
Component_set{recorder});
660 const auto recordsBeforeSample = recorder->records.size();
663 const std::vector<Simulator::WaveformInputDriver> inputDrivers{{input, {}}};
665 EXPECT_EQ(simulator.simulateWaveform(1, inputSnapshots, inputDrivers),
667 EXPECT_EQ(recorder->records.size(), recordsBeforeSample);
671TEST(SimulatorTest, UpdateBusRequiresExactWidthForImmediateAndDelayedValues)
674 auto circuit = std::make_shared<Circuit>();
678 std::invalid_argument);
684 std::invalid_argument);
694TEST(SimulatorTest, DelayedGateRejectsShortInputPulse)
700 auto gate = std::make_shared<AndGate>(std::vector<Wire_ptr>{a, b}, o);
701 gate->setProperty(
"delay", 10);
703 auto circuit = std::make_shared<Circuit>(
Component_set{gate});
716TEST(SimulatorTest, DelayedGateReplacesPendingTransition)
722 auto gate = std::make_shared<AndGate>(std::vector<Wire_ptr>{a, b}, o);
723 gate->setProperty(
"delay", 10);
725 auto circuit = std::make_shared<Circuit>(
Component_set{gate});
738TEST(SimulatorTest, DelayedGateReevaluationDoesNotPostponePendingTransition)
740 auto input = std::make_shared<Wire>(
State::LOW);
744 auto notGate = std::make_shared<CountingNotGate>(input, inverted);
745 notGate->setProperty(
"delay", 7);
748 std::make_shared<AndGate>(std::vector<Wire_ptr>{input, inverted}, output);
749 andGate->setProperty(
"delay", 5);
751 auto circuit = std::make_shared<Circuit>(
Component_set{notGate, andGate});
755 EXPECT_EQ(output->getCurrentState(),
State::LOW);
757 EXPECT_EQ(notGate->simulateCount, 1);
760 EXPECT_EQ(inverted->getCurrentState(),
State::HIGH);
761 EXPECT_EQ(notGate->simulateCount, 1);
764TEST(SimulatorTest, ForwardPropagationDoesNotRescheduleIndependentDelayedBranch)
774 auto first = std::make_shared<AndGate>(std::vector<Wire_ptr>{a1, b1}, o1);
775 first->setProperty(
"delay", 10);
777 auto second = std::make_shared<AndGate>(std::vector<Wire_ptr>{a2, b2}, o2);
778 second->setProperty(
"delay", 10);
780 auto circuit = std::make_shared<Circuit>(
Component_set{first, second});
792TEST(SimulatorTest, RunUntilIdlePropagatesThroughLongDelayChain)
800 auto first = std::make_shared<AndGate>(std::vector<Wire_ptr>{a, b}, w);
801 first->setProperty(
"delay", 50);
803 auto second = std::make_shared<AndGate>(std::vector<Wire_ptr>{w, c}, o);
804 second->setProperty(
"delay", 50);
806 auto circuit = std::make_shared<Circuit>(
Component_set{first, second});
810 EXPECT_EQ(simulator.getCurrentTime(), 100);
814TEST(SimulatorTest, RunUntilIdleStopsAtStepLimitForDelayedFeedback)
819 auto wire = std::make_shared<Wire>(
State::LOW);
820 auto gate = std::make_shared<NotGate>(wire, wire);
821 gate->setProperty(
"delay", 1);
823 auto circuit = std::make_shared<Circuit>(
Component_set{gate});
827 EXPECT_EQ(simulator.getCurrentTime(), 3);
832TEST(FlipFlopTest, DFlipFlopCapturesOnPositiveEdge)
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);
841 auto flipFlop = std::make_shared<DFlipFlop>(d, clock, clear, preset, q, notQ);
842 flipFlop->setProperty(
"propagationDelay", 0);
844 auto circuit = std::make_shared<Circuit>(
Component_set{flipFlop});
854 EXPECT_EQ(notQ->getCurrentState(),
State::LOW);
870TEST(FlipFlopTest, DFlipFlopCapturesOnNegativeEdge)
874 auto clear = std::make_shared<Wire>(
State::LOW);
875 auto preset = std::make_shared<Wire>(
State::LOW);
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"));
883 auto circuit = std::make_shared<Circuit>(
Component_set{flipFlop});
891 EXPECT_EQ(notQ->getCurrentState(),
State::LOW);
905TEST(FlipFlopTest, EFlipFlopHonorsEnable)
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);
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});
926 EXPECT_EQ(simulator.setBus(
Bus{enable},
valueFor(
Bus{enable}, 1)),
931 EXPECT_EQ(notQ->getCurrentState(),
State::LOW);
935 EXPECT_EQ(simulator.setBus(
Bus{enable},
valueFor(
Bus{enable}, 0)),
942 EXPECT_EQ(notQ->getCurrentState(),
State::LOW);
945TEST(FlipFlopTest, DLatchIsTransparentWhileEnabledAndHoldsWhileDisabled)
948 auto enable = std::make_shared<Wire>(
State::LOW);
952 auto latch = std::make_shared<DLatch>(d, enable, q, notQ);
953 latch->setProperty(
"propagationDelay", 0);
955 auto circuit = std::make_shared<Circuit>(
Component_set{latch});
963 EXPECT_EQ(simulator.setBus(
Bus{enable},
valueFor(
Bus{enable}, 1)),
966 EXPECT_EQ(notQ->getCurrentState(),
State::LOW);
973 EXPECT_EQ(simulator.setBus(
Bus{enable},
valueFor(
Bus{enable}, 0)),
981TEST(FlipFlopTest, DLatchUnknownEnableInvalidatesStoredState)
988 auto latch = std::make_shared<DLatch>(d, enable, q, notQ);
989 latch->setProperty(
"propagationDelay", 0);
991 auto circuit = std::make_shared<Circuit>(
Component_set{latch});
997 const std::array changedBuses{
Bus{enable}};
998 latch->simulate(simulator,
1004TEST(FlipFlopTest, DLatchPropagationDelayDefersTransparentUpdates)
1007 auto enable = std::make_shared<Wire>(
State::LOW);
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);
1015 auto circuit = std::make_shared<Circuit>(
Component_set{latch});
1018 EXPECT_EQ(simulator.setBus(
Bus{enable},
valueFor(
Bus{enable}, 1)),
1025 EXPECT_EQ(notQ->getCurrentState(),
State::LOW);
1028TEST(FlipFlopTest, JKFlipFlopImplementsTruthTable)
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);
1038 auto flipFlop = std::make_shared<JKFlipFlop>(j, k, clock, clear, preset, q, notQ);
1039 flipFlop->setProperty(
"propagationDelay", 0);
1041 auto circuit = std::make_shared<Circuit>(
Component_set{flipFlop});
1077 EXPECT_EQ(notQ->getCurrentState(),
State::LOW);
1087TEST(FlipFlopTest, AsyncClearAndPresetOverrideInputs)
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);
1096 auto flipFlop = std::make_shared<DFlipFlop>(d, clock, clear, preset, q, notQ);
1097 flipFlop->setProperty(
"propagationDelay", 0);
1099 auto circuit = std::make_shared<Circuit>(
Component_set{flipFlop});
1109 EXPECT_EQ(simulator.setBus(
Bus{preset},
valueFor(
Bus{preset}, 1)),
1112 EXPECT_EQ(notQ->getCurrentState(),
State::LOW);
1120TEST(FlipFlopTest, UnconnectedAsyncControlsDefaultInactive)
1123 auto clock = std::make_shared<Wire>(
State::LOW);
1127 auto flipFlop = std::make_shared<DFlipFlop>(d, clock,
Wire_ptr{},
Wire_ptr{}, q, notQ);
1128 flipFlop->setProperty(
"propagationDelay", 0);
1136 auto circuit = std::make_shared<Circuit>(
Component_set{flipFlop});
1142 EXPECT_EQ(notQ->getCurrentState(),
State::LOW);
1145TEST(FlipFlopTest, UnconnectedAsyncControlsRemainInactiveAfterClearingWires)
1148 auto clock = std::make_shared<Wire>(
State::LOW);
1154 flipFlop->setProperty(
"propagationDelay", 0);
1155 flipFlop->clearWires();
1158 flipFlop->setOutput(0,
Bus{q});
1159 flipFlop->setOutput(1,
Bus{notQ});
1161 auto circuit = std::make_shared<Circuit>(
Component_set{flipFlop});
1167 EXPECT_EQ(notQ->getCurrentState(),
State::LOW);
1170TEST(FlipFlopTest, UnknownDataCapturesAsUnknown)
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);
1179 auto flipFlop = std::make_shared<DFlipFlop>(d, clock, clear, preset, q, notQ);
1180 flipFlop->setProperty(
"propagationDelay", 0);
1182 auto circuit = std::make_shared<Circuit>(
Component_set{flipFlop});
1191TEST(FlipFlopTest, ZeroPropagationDelayUpdatesImmediately)
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);
1200 auto flipFlop = std::make_shared<DFlipFlop>(d, clock, clear, preset, q, notQ);
1201 flipFlop->setProperty(
"propagationDelay", 0);
1203 auto circuit = std::make_shared<Circuit>(
Component_set{flipFlop});
1209 EXPECT_EQ(notQ->getCurrentState(),
State::LOW);
1212TEST(FlipFlopTest, ZeroDelayChainCapturesFromPreEdgeSnapshot)
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);
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);
1232 auto circuit = std::make_shared<Circuit>(
Component_set{ff0, ff1, ff2});
1239 EXPECT_EQ(q0->getCurrentState(),
State::LOW);
1240 EXPECT_EQ(q1->getCurrentState(),
State::LOW);
1241 EXPECT_EQ(q2->getCurrentState(),
State::LOW);
1249 EXPECT_EQ(q1->getCurrentState(),
State::LOW);
1250 EXPECT_EQ(q2->getCurrentState(),
State::LOW);
1259 EXPECT_EQ(q2->getCurrentState(),
State::LOW);
1262TEST(FlipFlopTest, ZeroDelayChainSamplesPreEdgeCombinationalValue)
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);
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);
1279 ff0->setProperty(
"propagationDelay", 0);
1280 ff1->setProperty(
"propagationDelay", 0);
1281 inverter->setProperty(
"delay", 0);
1283 auto circuit = std::make_shared<Circuit>(
Component_set{ff0, inverter, ff1});
1290 EXPECT_EQ(q0->getCurrentState(),
State::LOW);
1292 EXPECT_EQ(q1->getCurrentState(),
State::LOW);
1300 EXPECT_EQ(invQ0->getCurrentState(),
State::LOW);
1304TEST(FlipFlopTest, DefaultPropagationDelayDefersOutputUpdates)
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);
1313 auto flipFlop = std::make_shared<DFlipFlop>(d, clock, clear, preset, q, notQ);
1314 EXPECT_EQ(flipFlop->getPropertyValue<
int>(
"propagationDelay").value_or(-1), 5);
1316 auto circuit = std::make_shared<Circuit>(
Component_set{flipFlop});
1330 EXPECT_EQ(notQ->getCurrentState(),
State::LOW);
1333TEST(FlipFlopTest, SetupViolationCapturesUnknown)
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);
1342 auto flipFlop = std::make_shared<DFlipFlop>(d, clock, clear, preset, q, notQ);
1343 flipFlop->setProperty(
"propagationDelay", 0);
1344 flipFlop->setProperty(
"setupTime", 3);
1346 auto circuit = std::make_shared<Circuit>(
Component_set{flipFlop});
1366TEST(FlipFlopTest, HoldViolationInvalidatesLatchedState)
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);
1375 auto flipFlop = std::make_shared<DFlipFlop>(d, clock, clear, preset, q, notQ);
1376 flipFlop->setProperty(
"propagationDelay", 0);
1377 flipFlop->setProperty(
"holdTime", 3);
1379 auto circuit = std::make_shared<Circuit>(
Component_set{flipFlop});
1394TEST(FlipFlopTest, EnabledFlipFlopAppliesSetupTimeToEnable)
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);
1404 auto flipFlop = std::make_shared<EFlipFlop>(d, enable, clock, clear, preset, q, notQ);
1405 flipFlop->setProperty(
"propagationDelay", 0);
1406 flipFlop->setProperty(
"setupTime", 4);
1408 auto circuit = std::make_shared<Circuit>(
Component_set{flipFlop});
1418 EXPECT_EQ(simulator.setBus(
Bus{enable},
valueFor(
Bus{enable}, 1)),
1428TEST(FlipFlopTest, JKFlipFlopAppliesHoldTimeToInputs)
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);
1438 auto flipFlop = std::make_shared<JKFlipFlop>(j, k, clock, clear, preset, q, notQ);
1439 flipFlop->setProperty(
"propagationDelay", 0);
1440 flipFlop->setProperty(
"holdTime", 5);
1442 auto circuit = std::make_shared<Circuit>(
Component_set{flipFlop});
1457TEST(FlipFlopTest, TimingPropertiesAreValidated)
1459 auto flipFlop = std::make_shared<DFlipFlop>();
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);
1468TEST(SimulatorTest, InteractiveSettlingKeepsWaveformChangesAtDistinctTimes)
1474 auto gate = std::make_shared<AndGate>(std::vector<Wire_ptr>{a, b}, o);
1475 gate->setProperty(
"delay", 0);
1477 auto circuit = std::make_shared<Circuit>(
Component_set{gate});
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);
1486 samples.push_back({time, std::move(values)});
1489 simulator.setTraceBuses({{
"input",
Bus{a}}, {
"output",
Bus{o}}});
1490 simulator.setTraceSink([&](uint64_t time,
const std::vector<BusValue>& values) {
1494 auto settleInteractive = [&simulator]() {
1495 const auto result = simulator.runUntilIdle();
1498 return simulator.run(1);
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,
1516 EXPECT_EQ(samples[2].values,
1520TEST(SimulatorTest, WaveformAppliesSameTimestampInputsTogether)
1526 auto gate = std::make_shared<XorGate>(std::array<Wire_ptr, 2>{a, b}, o);
1527 gate->setProperty(
"delay", 0);
1529 auto circuit = std::make_shared<Circuit>(
Component_set{gate});
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]);
1538 tracedValues.clear();
1540 const std::vector<Sample> inputSnapshots{
1544 const std::vector<Simulator::WaveformInputDriver> inputDrivers{
1549 EXPECT_EQ(simulator.simulateWaveform(5, inputSnapshots, inputDrivers),
1552 EXPECT_TRUE(std::ranges::none_of(tracedValues, [](
const BusValue& value) {
1561 auto o = std::make_shared<Wire>();
1563 auto g = std::make_shared<NandGate>(std::vector<Wire_ptr>{a, b}, o);
1579 auto o = std::make_shared<Wire>();
1581 auto g = std::make_shared<OrGate>(std::vector<Wire_ptr>{a, b}, o);
1587 <<
"OR(ERROR, ERROR) = " <<
to_str(o->getCurrentState());
1590 sim.simulateBus(
Bus{o});
1593 <<
"OR(ERROR, HIGH) = " <<
to_str(o->getCurrentState());
1596 sim.simulateBus(
Bus{o});
1599 <<
"OR(ERROR, LOW) = " <<
to_str(o->getCurrentState());
1605 <<
"OR(LOW, LOW) = " <<
to_str(o->getCurrentState());
1610 <<
"OR(HIGH, LOW) = " <<
to_str(o->getCurrentState());
1615 <<
"OR(HIGH, HIGH) = " <<
to_str(o->getCurrentState());
1622 auto o = std::make_shared<Wire>();
1624 auto g = std::make_shared<NorGate>(std::vector<Wire_ptr>{a, b}, o);
1640 auto o = std::make_shared<Wire>();
1642 auto g = std::make_shared<XorGate>(std::array<Wire_ptr, 2>{a, b}, o);
1648 <<
"XOR(ERROR, ERROR) = " <<
to_str(o->getCurrentState());
1651 sim.simulateBus(
Bus{o});
1654 <<
"XOR(ERROR, HIGH) = " <<
to_str(o->getCurrentState());
1657 sim.simulateBus(
Bus{o});
1660 <<
"XOR(ERROR, LOW) = " <<
to_str(o->getCurrentState());
1666 <<
"XOR(LOW, LOW) = " <<
to_str(o->getCurrentState());
1671 <<
"XOR(HIGH, LOW) = " <<
to_str(o->getCurrentState());
1676 <<
"XOR(HIGH, HIGH) = " <<
to_str(o->getCurrentState());
1683 auto o = std::make_shared<Wire>();
1686 auto g = std::make_shared<XorGate>(std::array<Wire_ptr, 2>{a, b}, o);
1694 auto g = std::make_shared<AndGate>(std::vector<Wire_ptr>{a, b}, o);
1703 auto g = std::make_shared<OrGate>(std::vector<Wire_ptr>{a, b}, o);
1717 auto o = std::make_shared<Wire>();
1719 auto ag = std::make_shared<AndGate>(std::vector<Wire_ptr>{a, b}, o);
1724 std::vector<Bus> newInputs = {{c}, {b}};
1725 ag->setInputs(newInputs);
1741TEST(LogicTest, TopologyEditUsesNewSimulator)
1748 auto gate = std::make_shared<AndGate>(std::vector<Wire_ptr>{a, b}, o);
1749 gate->setProperty(
"delay", 0);
1752 auto circuit = std::make_shared<Circuit>(
Component_set{gate});
1759 std::vector<Bus> newInputs = {{c}, {b}};
1760 gate->setInputs(newInputs);
1762 auto circuit = std::make_shared<Circuit>(
Component_set{gate});
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)));
1780TEST(LogicTest, BusSettingReadingAtUnsignedIntWidth)
1782 Bus bus(std::numeric_limits<unsigned int>::digits);
1787 valueFor(bus, std::numeric_limits<unsigned int>::max()));
1793TEST(LogicTest, BusAssignmentsNormalizeWidthAndReportMeaningfulOverflow)
1810TEST(LogicTest, DisconnectedBusStateQueriesDoNotDereferenceNullWires)
1824TEST(LogicTest, GateBitwiseDefaultsAndValidation)
1826 auto a = std::make_shared<Wire>();
1827 auto b = std::make_shared<Wire>();
1828 auto o = std::make_shared<Wire>();
1830 auto gate = std::make_shared<AndGate>(std::vector<Wire_ptr>{a, b}, o);
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);
1838 EXPECT_THROW(gate->setProperty(
"size", 0), std::invalid_argument);
1839 EXPECT_THROW(gate->setProperty(
"size", -2), std::invalid_argument);
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);
1847 notGate->setProperty(
"size", 4);
1848 EXPECT_EQ(notGate->inputBuses()[0].size(), 4);
1849 EXPECT_EQ(notGate->outputBuses()[0].size(), 4);
1852TEST(LogicTest, GateBitwiseReshapesIO)
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>());
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);
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);
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);
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);
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);
1886TEST(LogicTest, ReductionGatesMatchSeparateScalarInputs)
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>(); },
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);
1911 auto circuit = std::make_shared<Circuit>(
Component_set{reduction, scalar},
false);
1914 EXPECT_EQ(reduction->outputBuses()[0][0]->getCurrentState(),
1915 scalar->outputBuses()[0][0]->getCurrentState())
1916 << reduction->typeName() <<
" pattern " << pattern;
1921TEST(LogicTest, AndBitwiseSimulation)
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);
1931 sim.setBus(gate->getInputs()[0],
valueFor(gate->getInputs()[0], 0b1101));
1932 sim.setBus(gate->getInputs()[1],
valueFor(gate->getInputs()[1], 0b1011));
1935 expectBusStates(gate->getOutputs()[0],
1936 {State::HIGH, State::LOW, State::LOW, State::HIGH});
1939TEST(LogicTest, OrBitwiseSimulation)
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);
1949 sim.setBus(gate->getInputs()[0],
valueFor(gate->getInputs()[0], 0b0101));
1950 sim.setBus(gate->getInputs()[1],
valueFor(gate->getInputs()[1], 0b1010));
1953 expectBusStates(gate->getOutputs()[0],
1954 {State::HIGH, State::HIGH, State::HIGH, State::HIGH});
1957TEST(LogicTest, NandBitwiseSimulation)
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);
1967 sim.setBus(gate->getInputs()[0],
valueFor(gate->getInputs()[0], 0b1101));
1968 sim.setBus(gate->getInputs()[1],
valueFor(gate->getInputs()[1], 0b1011));
1971 expectBusStates(gate->getOutputs()[0],
1972 {State::LOW, State::HIGH, State::HIGH, State::LOW});
1975TEST(LogicTest, NorBitwiseSimulation)
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);
1985 sim.setBus(gate->getInputs()[0],
valueFor(gate->getInputs()[0], 0b0101));
1986 sim.setBus(gate->getInputs()[1],
valueFor(gate->getInputs()[1], 0b1000));
1989 expectBusStates(gate->getOutputs()[0],
1990 {State::LOW, State::HIGH, State::LOW, State::LOW});
1993TEST(LogicTest, XorBitwiseSimulationPreservesUnknownAndErrorPerBit)
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);
2001 auto inputs = gate->getInputs();
2002 inputs[0][0]->forceSetCurrentState(
State::LOW);
2007 inputs[1][2]->forceSetCurrentState(
State::LOW);
2015 expectBusStates(gate->getOutputs()[0],
2016 {State::HIGH, State::LOW, State::UNKNOWN, State::ERROR});
2019TEST(LogicTest, NotGateSimulatesVectorAndLogicalInputs)
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);
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);
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);
2042 auto circuit = std::make_shared<Circuit>(
2043 Component_set{vectorNot, logicalNot, unknownLogicalNot},
false);
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});
2055TEST(ComponentTest, SetAndGetIntProperty)
2057 struct TestComponent :
public Component {
2059 std::string_view
typeName()
const override {
return "TestComponent"; }
2063 auto c = std::make_shared<TestComponent>();
2065 auto prop = c->getProperty(
"value");
2066 ASSERT_TRUE(prop.has_value());
2067 EXPECT_EQ(std::get<int>(*prop), 10);
2069 c->setProperty(
"value", 20);
2070 prop = c->getProperty(
"value");
2071 EXPECT_EQ(std::get<int>(*prop), 20);
2074TEST(ComponentTest, UnconnectedInputMayDeclareDefaultState)
2076 DefaultedInputTestComponent component;
2077 EXPECT_EQ(component.unconnectedInputDefault(0),
State::HIGH);
2080 auto low = std::make_shared<Wire>(
State::LOW);
2081 component.setInput(0,
Bus{low});
2082 EXPECT_EQ(component.readInput(),
State::LOW);
2085TEST(ComponentTest, SetAndGetIntPropertyTemplated)
2087 struct TestComponent :
public Component {
2089 std::string_view
typeName()
const override {
return "TestComponent"; }
2093 auto c = std::make_shared<TestComponent>();
2095 auto prop = c->getPropertyValue<
int>(
"value");
2096 ASSERT_TRUE(prop.has_value());
2097 EXPECT_EQ(*prop, 10);
2099 c->setPropertyValue<
int>(
"value", 20);
2100 prop = c->getPropertyValue<
int>(
"value");
2101 EXPECT_EQ(*prop, 20);
2104TEST(ComponentTest, SetAndGetBoolProperty)
2106 struct TestComponent :
public Component {
2108 std::string_view
typeName()
const override {
return "TestComponent"; }
2112 auto c = std::make_shared<TestComponent>();
2114 auto prop = c->getProperty(
"enabled");
2115 ASSERT_TRUE(prop.has_value());
2116 EXPECT_EQ(std::get<bool>(*prop),
false);
2118 c->setProperty(
"enabled",
true);
2119 prop = c->getProperty(
"enabled");
2120 EXPECT_EQ(std::get<bool>(*prop),
true);
2123TEST(ComponentTest, SetAndGetStringProperty)
2125 struct TestComponent :
public Component {
2130 std::string_view
typeName()
const override {
return "TestComponent"; }
2134 auto c = std::make_shared<TestComponent>();
2136 auto prop = c->getProperty(
"name");
2137 ASSERT_TRUE(prop.has_value());
2138 EXPECT_EQ(std::get<std::string>(*prop),
"default");
2140 c->setProperty(
"name", std::string(
"custom"));
2141 prop = c->getProperty(
"name");
2142 EXPECT_EQ(std::get<std::string>(*prop),
"custom");
2145TEST(ComponentTest, SetAndGetBusValueProperty)
2147 struct TestComponent :
public Component {
2149 std::string_view
typeName()
const override {
return "TestComponent"; }
2153 auto component = std::make_shared<TestComponent>();
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);
2161TEST(ComponentTest, SetAndGetStringListProperty)
2163 auto c = std::make_shared<StringListPropertyTestComponent>();
2165 auto prop = c->getPropertyValue<std::string>(
"orientation");
2166 ASSERT_TRUE(prop.has_value());
2167 EXPECT_EQ(*prop,
"DOWN");
2169 const auto options = c->getStringPropertyOptions(
"orientation");
2170 ASSERT_TRUE(options.has_value());
2171 EXPECT_EQ(options->get().size(), 4);
2173 c->setProperty(
"orientation", std::string(
"LEFT"));
2174 EXPECT_EQ(c->getPropertyValue<std::string>(
"orientation").value(),
"LEFT");
2177TEST(ComponentTest, StringListPropertyRejectsInvalidValues)
2179 auto c = std::make_shared<StringListPropertyTestComponent>();
2181 EXPECT_THROW(c->setProperty(
"orientation", std::string(
"DIAGONAL")),
2182 std::invalid_argument);
2183 EXPECT_EQ(c->getPropertyValue<std::string>(
"orientation").value(),
"DOWN");
2186TEST(ComponentTest, StringListPropertyRejectsInvalidDefault)
2188 EXPECT_THROW((
void)std::make_shared<StringListPropertyTestComponent>(
"DIAGONAL"),
2189 std::invalid_argument);
2192TEST(ComponentTest, StringListPropertyRejectsInvalidCallbackResult)
2194 auto c = std::make_shared<StringListPropertyTestComponent>();
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");
2203TEST(ComponentTest, GetPropertyNotFound)
2205 struct TestComponent :
public Component {
2207 std::string_view
typeName()
const override {
return "TestComponent"; }
2211 auto c = std::make_shared<TestComponent>();
2213 auto prop = c->getProperty(
"nonexistent");
2214 EXPECT_FALSE(prop.has_value());
2217TEST(ComponentTest, SetPropertyTypeMismatch)
2219 struct TestComponent :
public Component {
2221 std::string_view
typeName()
const override {
return "TestComponent"; }
2225 auto c = std::make_shared<TestComponent>();
2227 EXPECT_THROW(c->setProperty(
"value", std::string(
"wrong type")), std::invalid_argument);
2230TEST(ComponentTest, SetPropertyUndefined)
2232 struct TestComponent :
public Component {
2234 std::string_view
typeName()
const override {
return "TestComponent"; }
2238 auto c = std::make_shared<TestComponent>();
2240 EXPECT_THROW(c->setProperty(
"undefined", 10), std::invalid_argument);
2245 struct TestComponent :
public Component {
2252 std::string_view
typeName()
const override {
return "TestComponent"; }
2256 auto c = std::make_shared<TestComponent>();
2257 auto props = c->getProperties();
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");
bool setCurrentValue(const BusValue &value, const Component_weakPtr &requestedBy)
bool forceSetCurrentValue(const BusValue &value)
bool isInErrorState() const
void setSize(unsigned short size)
BusValue getCurrentValue() const
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.
Executes event-driven simulation of a Circuit.
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)
std::shared_ptr< Wire > Wire_ptr
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)
std::set< Component_ptr, std::owner_less< Component_ptr > > Component_set
BusValue twosComplement(const BusValue &n)
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)
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
Context describing why a component is being evaluated.
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.
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.
BusValue valueFor(const Bus &bus, const std::uint64_t value)