SILICON
Loading...
Searching...
No Matches
component.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 "component.hpp"
19
20#include <algorithm>
21#include <limits>
22#include <ranges>
23#include <stdexcept>
24
26
27namespace SILICON::core {
28
29PropertyValue requireNonNegative(const std::string_view name,
30 const PropertyValue& value)
31{
32 if (std::get<int>(value) < 0) {
33 throw std::invalid_argument(std::format("{} must be non-negative", name));
34 }
35 return value;
36}
37
38PropertyValue requireValidSize(const std::string_view name,
39 const PropertyValue& value)
40{
41 const int size = std::get<int>(value);
42 if (size < 1)
43 throw std::invalid_argument(std::format("{} must be at least 1", name));
44 if (size > std::numeric_limits<unsigned short>::max())
45 throw std::invalid_argument(std::format("{} is too large", name));
46 return value;
47}
48
49Component::Component(std::vector<Bus> inputs, std::vector<Bus> outputs)
50 : inputs(std::move(inputs)), outputs(std::move(outputs))
51{
52}
53
55{
56 const std::string type = std::string(typeName());
57 return {type, type, ComponentCategory::Utils};
58}
59
61{
62 uint64_t id = ++nextIoListenerId;
63 ioListeners[id] = std::move(cb);
64 return id;
65}
66
68{
69 ioListeners.erase(id);
70}
71
73{
74 for (auto& [id, cb] : ioListeners) {
75 cb(this);
76 }
77}
78
79void Component::defineStringListProperty(std::string key, std::string defaultValue,
80 StringPropertyOptions allowedValues,
81 PropertyCallback callback)
82{
83 if (allowedValues.empty()) {
84 throw std::invalid_argument(std::format(
85 "String-list property '{}' on component '{}' must define allowed values", key,
86 typeName()));
87 }
88
89 const bool defaultAllowed = std::ranges::contains(allowedValues, defaultValue);
90 if (!defaultAllowed) {
91 throw std::invalid_argument(std::format(
92 "Default value '{}' is not allowed for property '{}' on component '{}'",
93 defaultValue, key, typeName()));
94 }
95
96 const std::string propertyKey = key;
97 stringPropertyOptions[key] = std::move(allowedValues);
98 defineProperty(std::move(key), std::move(defaultValue), std::move(callback));
99 const auto& propertyValue = properties.at(propertyKey);
100 validatePropertyValue(propertyKey, propertyValue, propertyValue);
101}
102
103void Component::validatePropertyValue(std::string_view key,
104 const PropertyValue& currentValue,
105 const PropertyValue& newValue) const
106{
107 if (currentValue.index() != newValue.index()) {
108 throw std::invalid_argument(std::format(
109 "Type mismatch when setting property '{}' on component '{}'", key, typeName()));
110 }
111
112 const auto options = stringPropertyOptions.find(key);
113 if (options == stringPropertyOptions.end())
114 return;
115
116 const auto* stringValue = std::get_if<std::string>(&newValue);
117 if (!stringValue || !std::ranges::contains(options->second, *stringValue)) {
118 throw std::invalid_argument(std::format(
119 "Invalid value for property '{}' on component '{}'", key, typeName()));
120 }
121}
122void Component::handleInputSizeChange(const unsigned int index,
123 const unsigned int newSize)
124{
125 const auto currentSize = inputs[index].size();
126 if (currentSize != newSize)
127 throw std::runtime_error(std::format(
128 "Input size mismatch, currently is {} but wants to be {}", currentSize, newSize));
129}
130
131void Component::replaceBus(std::vector<Bus>& busCollection, const unsigned int index,
132 Bus newBus)
133{
134 if (busCollection.size() > index && busCollection[index] == newBus)
135 return;
136 if (busCollection.size() <= index)
137 busCollection.resize(index + 1);
138 busCollection[index] = std::move(newBus);
139}
140
141// --- Properties Management -------------------------------------------------------------
142
143void Component::setProperty(std::string_view key, const PropertyValue& value)
144{
145 auto it = properties.find(key);
146
147 // Enforce static set of properties
148 if (it == properties.end()) {
149 throw std::invalid_argument(
150 std::format("Property '{}' does not exist on component '{}'", key, typeName()));
151 }
152
153 validatePropertyValue(key, it->second, value);
154
155 // Call callback if it's registered. Update the value accordingly
156 auto cbIt = propertyCallbacks.find(key);
157
158 PropertyValue finalValue =
159 (cbIt == propertyCallbacks.end()) ? value : cbIt->second(value);
160
161 validatePropertyValue(key, it->second, finalValue);
162 it->second = std::move(finalValue);
163}
164
165std::optional<PropertyValue> Component::getProperty(std::string_view key) const
166{
167 if (const auto it = properties.find(key); it != properties.end()) {
168 return it->second;
169 }
170 return std::nullopt;
171}
172
173std::optional<std::reference_wrapper<const StringPropertyOptions>>
174Component::getStringPropertyOptions(std::string_view key) const
175{
176 if (const auto it = stringPropertyOptions.find(key);
177 it != stringPropertyOptions.end()) {
178 return std::cref(it->second);
179 }
180 return std::nullopt;
181}
182
183void Component::setPropertyCallback(std::string_view key, PropertyCallback callback)
184{
185 const auto property = properties.find(key);
186 if (property == properties.end()) {
187 throw std::invalid_argument(
188 std::format("Property '{}' does not exist on component '{}'", key, typeName()));
189 }
190
191 propertyCallbacks.insert_or_assign(std::string(key), std::move(callback));
192 PropertyValue finalValue = propertyCallbacks.find(key)->second(property->second);
193 validatePropertyValue(key, property->second, finalValue);
194 property->second = std::move(finalValue);
195}
196
197void Component::setInput(const unsigned int index, const Bus& bus, const bool checkSize)
198{
199 if (this->inputs.size() > index && this->inputs[index] == bus)
200 return;
201
202 if (checkSize)
203 handleInputSizeChange(index, bus.size());
204 replaceBus(this->inputs, index, bus);
206}
207
208void Component::setOutput(const unsigned int index, const Bus& bus)
209{
210 if (this->outputs.size() > index && this->outputs[index] == bus)
211 return;
212 replaceBus(this->outputs, index, bus);
214}
215
216void Component::setInputs(const std::vector<Bus>& newInputs)
217{
218 if (this->inputs == newInputs)
219 return;
220 this->inputs.resize(newInputs.size());
221 for (auto [index, bus] : newInputs | SILICON::views::enumerate) {
222 replaceBus(this->inputs, index, bus);
223 }
225}
226
227void Component::setOutputs(const std::vector<Bus>& newOutputs)
228{
229 if (this->outputs == newOutputs)
230 return;
231 this->outputs.resize(newOutputs.size());
232 for (auto [index, bus] : newOutputs | SILICON::views::enumerate) {
233 replaceBus(this->outputs, index, bus);
234 }
236}
237
238bool Component::isConnectedTo(const Bus& b) const
239{
240 return std::ranges::contains(allBuses(), b);
241}
242
244{
245 for (auto& bus :
246 std::array{std::span<Bus>(inputs), std::span<Bus>(outputs)} | std::views::join)
247 bus = Bus(std::vector<Wire_ptr>(bus.size()));
249}
250
251} // namespace SILICON::core
std::function< void(Component *)> IOObserver
Callback type for I/O change notifications.
bool isConnectedTo(const Bus &b) const
Checks if this component is connected to a bus.
void removeIOListener(uint64_t id)
Removes a previously added I/O listener.
Definition component.cpp:67
std::optional< PropertyValue > getProperty(std::string_view key) const
Gets a property value.
virtual std::string_view typeName() const =0
Gets the component type name.
auto allBuses() const
Borrows all buses, inputs first, without copying or deduplicating.
StringPropertyOptionsMap stringPropertyOptions
Allowed values for constrained string properties.
void setOutputs(const std::vector< Bus > &newOutputs)
Replaces all output buses.
void setInput(unsigned int index, const Bus &bus, bool checkSize=false)
Sets an input bus at a specific index.
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 defineStringListProperty(std::string key, std::string defaultValue, StringPropertyOptions allowedValues, PropertyCallback callback=nullptr)
Defines a string property constrained to a fixed set of values.
Definition component.cpp:79
PropertyMap properties
Map of configurable properties for this component.
void setOutput(unsigned int index, const Bus &bus)
Sets an output bus at a specific index.
void replaceBus(std::vector< Bus > &busCollection, unsigned int index, Bus newBus)
Replaces a bus in the input or output collection.
void setPropertyCallback(std::string_view key, PropertyCallback callback)
Sets a callback for property validation/transformation.
virtual void clearWires()
Clears all wire connections.
PropertyCallbackMap propertyCallbacks
Map of callbacks for property validation/transformation.
uint64_t addIOListener(IOObserver cb)
Adds a listener for I/O changes.
Definition component.cpp:60
virtual ComponentMetadata metadata() const
Gets catalog metadata for this component type.
Definition component.cpp:54
uint64_t nextIoListenerId
Counter for generating unique I/O listener IDs.
std::optional< std::reference_wrapper< const StringPropertyOptions > > getStringPropertyOptions(std::string_view key) const
Gets allowed values for a constrained string property.
void defineProperty(std::string key, T &&defaultValue, PropertyCallback callback=nullptr)
Defines a property with a default value and optional callback.
void notifyIOListeners()
Notifies all registered I/O listeners of a change.
Definition component.cpp:72
std::unordered_map< uint64_t, IOObserver > ioListeners
Map of I/O change listeners indexed by ID.
void handleInputSizeChange(const unsigned int index, const unsigned int newSize)
Handles input size changes. By default input size shouldn't change automatically.
void validatePropertyValue(std::string_view key, const PropertyValue &currentValue, const PropertyValue &newValue) const
Validates a property value against the declared type and metadata.
std::function< PropertyValue(const PropertyValue &)> PropertyCallback
Callback function for property validation/transformation.
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
std::vector< std::string > StringPropertyOptions
Allowed values for a constrained string property.