SILICON
Loading...
Searching...
No Matches
utils.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 "utils.hpp"
19
20#include <algorithm>
21#include <charconv>
22#include <limits>
23#include <numeric>
24#include <stdexcept>
25
26#include <core/simulator.hpp>
27
28namespace SILICON::extra {
29using namespace SILICON::core;
30
31namespace {
32 unsigned int parseWidth(const std::string_view text, const bool allowZero = false)
33 {
34 unsigned int value = 0;
35 const auto [end, error] =
36 std::from_chars(text.data(), text.data() + text.size(), value);
37 if (text.empty() || error != std::errc{} || end != text.data() + text.size()
38 || (!allowZero && value == 0)
39 || value > std::numeric_limits<unsigned short>::max())
40 throw std::invalid_argument("Invalid splitter/merger bit range or width");
41 return value;
42 }
43
44 template <typename Callback> void parseList(std::string_view text, Callback callback)
45 {
46 while (!text.empty()) {
47 const auto comma = text.find(',');
48 callback(text.substr(0, comma));
49 if (comma == std::string_view::npos)
50 return;
51 text.remove_prefix(comma + 1);
52 if (text.empty())
53 throw std::invalid_argument("Splitter/merger list has a trailing comma");
54 }
55 }
56
57 std::vector<Bus> resizedBuses(const std::vector<Bus>& buses,
58 const std::vector<unsigned int>& widths)
59 {
60 std::vector<Bus> result;
61 result.reserve(widths.size());
62 for (std::size_t i = 0; i < widths.size(); ++i)
63 result.push_back(i < buses.size() && buses[i].size() == widths[i]
64 ? buses[i]
65 : Bus(static_cast<unsigned short>(widths[i])));
66 return result;
67 }
68} // namespace
69
74
75WireSplitter::WireSplitter(Bus input, const std::vector<Bus>& outputs) : WireSplitter()
76{
77 this->inputs = {std::move(input)};
78 this->outputs = outputs;
79 setProperty("size",
80 this->inputs[0].size() == 0 ? 2 : static_cast<int>(this->inputs[0].size()));
81}
82
84{
85 // Default-constructed components are used by the registry and must keep empty
86 // buses. The size callback only reshapes I/O after real buses have been attached.
87 defineProperty("size", 2);
88 defineProperty("delay", 0);
89 defineProperty("slices", std::string{});
90
91 setPropertyCallback("delay", [](const PropertyValue& value) {
92 return requireNonNegative("WireSplitter delay", value);
93 });
94
95 setPropertyCallback("size", [this](const PropertyValue& value) {
96 const int newSize = std::get<int>(requireValidSize("WireSplitter size", value));
97 for (const auto& [offset, width] : slices)
98 if (offset + width > static_cast<unsigned int>(newSize))
99 throw std::invalid_argument("WireSplitter slice exceeds its input width");
100 if (!this->inputs.empty())
101 this->setSize(newSize);
102 return value;
103 });
104 setPropertyCallback("slices", [this](const PropertyValue& value) {
105 return setSlices(std::get<std::string>(value));
106 });
107}
108
109int WireSplitter::setSize(int newSize)
110{
111 (void)requireValidSize("WireSplitter size", newSize);
112 std::vector<unsigned int> outputWidths;
113 if (slices.empty()) {
114 outputWidths.assign(newSize, 1);
115 } else {
116 for (const auto& [offset, width] : slices) {
117 if (offset + width > static_cast<unsigned int>(newSize))
118 throw std::invalid_argument("WireSplitter slice exceeds its input width");
119 outputWidths.push_back(width);
120 }
121 }
122 setInputs(resizedBuses(inputs, {static_cast<unsigned int>(newSize)}));
123 setOutputs(resizedBuses(outputs, outputWidths));
124
125 return newSize;
126}
127
128std::string WireSplitter::setSlices(const std::string& specification)
129{
130 std::vector<std::pair<unsigned int, unsigned int>> parsed;
131 const auto size = getPropertyValue<int>("size").value_or(2);
132 parseList(specification, [&](const std::string_view item) {
133 const auto colon = item.find(':');
134 if (colon == std::string_view::npos)
135 throw std::invalid_argument("WireSplitter slices use offset:width pairs");
136 const auto offset = parseWidth(item.substr(0, colon), true);
137 const auto width = parseWidth(item.substr(colon + 1));
138 if (offset + width > static_cast<unsigned int>(size))
139 throw std::invalid_argument("WireSplitter slice exceeds its input width");
140 parsed.emplace_back(offset, width);
141 });
142 slices = std::move(parsed);
143 if (!inputs.empty())
144 setSize(size);
145 return specification;
146}
147
148std::vector<std::pair<unsigned int, unsigned int>> WireSplitter::outputSlices() const
149{
150 if (!slices.empty())
151 return slices;
152 std::vector<std::pair<unsigned int, unsigned int>> result;
153 const auto size = inputs.empty() ? getPropertyValue<int>("size").value_or(2)
154 : static_cast<int>(inputs[0].size());
155 for (int i = 0; i < size; ++i)
156 result.emplace_back(i, 1);
157 return result;
158}
159
161{
162 const int delay = getPropertyValue<int>("delay").value();
163 if (inputs.empty())
164 return;
165 const auto ranges = outputSlices();
166 for (std::size_t port = 0; port < outputs.size() && port < ranges.size(); ++port)
167 for (unsigned int bit = 0; bit < outputs[port].size() && bit < ranges[port].second;
168 ++bit)
169 sim.updateWire(outputs[port][bit],
170 Wire::safeGetCurrentState(inputs[0][ranges[port].first + bit]),
171 delay, weak_from_this());
172}
173
178
179WireMerger::WireMerger(const std::vector<Bus>& inputs, Bus output) : WireMerger()
180{
181 this->inputs = inputs;
182 this->outputs = {std::move(output)};
183 setProperty("size", this->outputs[0].size() == 0
184 ? 2
185 : static_cast<int>(this->outputs[0].size()));
186}
187
189{
190 // Default-constructed components are used by the registry and must keep empty
191 // buses. The size callback only reshapes I/O after real buses have been attached.
192 defineProperty("size", 2);
193 defineProperty("delay", 0);
194 defineProperty("widths", std::string{});
195
196 setPropertyCallback("delay", [](const PropertyValue& value) {
197 return requireNonNegative("WireMerger delay", value);
198 });
199
200 setPropertyCallback("size", [this](const PropertyValue& value) {
201 const int newSize = std::get<int>(requireValidSize("WireMerger size", value));
202 if (!widths.empty()
203 && std::accumulate(widths.begin(), widths.end(), 0u)
204 != static_cast<unsigned int>(newSize))
205 throw std::invalid_argument("WireMerger input widths must sum to its output width");
206 if (!this->outputs.empty())
207 this->setSize(newSize);
208 return value;
209 });
210 setPropertyCallback("widths", [this](const PropertyValue& value) {
211 return setWidths(std::get<std::string>(value));
212 });
213}
214
215int WireMerger::setSize(int newSize)
216{
217 (void)requireValidSize("WireMerger size", newSize);
218 if (!widths.empty()
219 && std::accumulate(widths.begin(), widths.end(), 0u)
220 != static_cast<unsigned int>(newSize))
221 throw std::invalid_argument("WireMerger input widths must sum to its output width");
222 setInputs(resizedBuses(inputs, widths.empty() ? std::vector<unsigned int>(newSize, 1)
223 : widths));
224 setOutputs(resizedBuses(outputs, {static_cast<unsigned int>(newSize)}));
225 return newSize;
226}
227
228std::string WireMerger::setWidths(const std::string& specification)
229{
230 std::vector<unsigned int> parsed;
231 parseList(specification,
232 [&](const std::string_view item) { parsed.push_back(parseWidth(item)); });
233 const auto size = getPropertyValue<int>("size").value_or(2);
234 if (!parsed.empty()
235 && std::accumulate(parsed.begin(), parsed.end(), std::uint64_t{0})
236 != static_cast<unsigned int>(size))
237 throw std::invalid_argument("WireMerger input widths must sum to its output width");
238 widths = std::move(parsed);
239 if (!outputs.empty())
240 setSize(size);
241 return specification;
242}
243
245{
246 const int delay = getPropertyValue<int>("delay").value();
247 if (outputs.empty())
248 return;
249 const auto inputWidths =
250 widths.empty() ? std::vector<unsigned int>(outputs[0].size(), 1) : widths;
251 unsigned int offset = 0;
252 for (std::size_t port = 0; port < inputWidths.size(); ++port)
253 for (unsigned int bit = 0; bit < inputWidths[port]; ++bit, ++offset) {
254 const State state =
255 port < inputs.size() && bit < inputs[port].size() && inputs[port][bit]
258 if (offset < outputs[0].size())
259 sim.updateWire(outputs[0][offset], state, delay, weak_from_this());
260 }
261}
262
263} // namespace SILICON::extra
void setOutputs(const std::vector< Bus > &newOutputs)
Replaces all output buses.
std::optional< T > getPropertyValue(std::string_view key) const
Gets a property value with type deduction.
std::vector< Bus > outputs
Output buses produced by this component.
void setInputs(const std::vector< Bus > &newInputs)
Replaces all input buses.
void setProperty(std::string_view key, const PropertyValue &value)
Sets a property value.
std::vector< Bus > inputs
Input buses connected to this component.
void setPropertyCallback(std::string_view key, PropertyCallback callback)
Sets a callback for property validation/transformation.
void defineProperty(std::string key, T &&defaultValue, PropertyCallback callback=nullptr)
Defines a property with a default value and optional callback.
static State safeGetCurrentState(const std::weak_ptr< Wire > &w)
Definition wire.cpp:245
int setSize(int newSize)
Definition utils.cpp:215
std::string setWidths(const std::string &specification)
Definition utils.cpp:228
void simulate(SILICON::simulation::Simulator &sim) override
Executes the component's logic.
Definition utils.cpp:244
std::vector< unsigned int > widths
Definition utils.hpp:62
int setSize(int newSize)
Definition utils.cpp:109
std::vector< std::pair< unsigned int, unsigned int > > outputSlices() const
Definition utils.cpp:148
std::string setSlices(const std::string &specification)
Definition utils.cpp:128
void simulate(SILICON::simulation::Simulator &sim) override
Executes the component's logic.
Definition utils.cpp:160
std::vector< std::pair< unsigned int, unsigned int > > slices
Definition utils.hpp:33
Executes event-driven simulation of a Circuit.
Definition simulator.hpp:74
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.
std::variant< int, bool, std::string, BusValue > PropertyValue
Variant type for component properties.
PropertyValue requireValidSize(const std::string_view name, const PropertyValue &value)
Validates that an integer property value is a valid bus size.
Definition component.cpp:38
PropertyValue requireNonNegative(const std::string_view name, const PropertyValue &value)
Validates that an integer property value is non-negative.
Definition component.cpp:29
QVariant value(const QSettings &settings, const Definition &setting)
Reads a setting value, falling back to its declared default when unset.