SILICON
Loading...
Searching...
No Matches
component.hpp
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#pragma once
19#include <array>
20#include <concepts>
21#include <functional>
22#include <memory>
23#include <optional>
24#include <ranges>
25#include <span>
26#include <string>
27#include <string_view>
28#include <type_traits>
29#include <unordered_map>
30#include <utility>
31#include <variant>
32#include <vector>
33
34#include <core/wire.hpp>
36
37namespace SILICON::yosys {
39}
40
42class Simulator;
43}
44
45namespace SILICON::core {
46
59
66enum class PortRole {
70};
71
78
79} // namespace SILICON::core
80
81namespace SILICON::simulation {
82
90struct Context {
92 bool initialEvaluation = false;
93
95 std::span<const core::Bus> changedBuses{};
96
98 std::unordered_map<uint64_t, core::State> previousWireStates{};
99
101 [[nodiscard]] bool changed(const core::Wire_ptr& wire) const
102 {
103 const auto previous = previousState(wire);
104 return previous.has_value() && wire && *previous != wire->getCurrentState();
105 }
106
108 [[nodiscard]] std::optional<core::State> previousState(const core::Wire_ptr& wire) const
109 {
110 if (!wire)
111 return std::nullopt;
112
113 const auto it = previousWireStates.find(wire->getId());
114 if (it == previousWireStates.end())
115 return std::nullopt;
116
117 return it->second;
118 }
119};
120
121} // namespace SILICON::simulation
122
123namespace SILICON::core {
124
132template <typename T>
133concept HasType = requires {
134 { T::Type } -> std::convertible_to<std::string_view>;
135};
136
142using PropertyValue = std::variant<int, bool, std::string, BusValue>;
143
145using PropertyMap = std::unordered_map<std::string, PropertyValue, TransparentStringHash,
147
149using PropertyCallback = std::function<PropertyValue(const PropertyValue&)>;
150
153 std::unordered_map<std::string, PropertyCallback, TransparentStringHash,
155
157using StringPropertyOptions = std::vector<std::string>;
158
161 std::unordered_map<std::string, StringPropertyOptions, TransparentStringHash,
163
171[[nodiscard]] PropertyValue requireNonNegative(std::string_view name,
172 const PropertyValue& value);
173
182[[nodiscard]] PropertyValue requireValidSize(std::string_view name,
183 const PropertyValue& value);
184
199class Component : public std::enable_shared_from_this<Component> {
200public:
209 using IOObserver = std::function<void(Component*)>;
210
211protected:
213 std::vector<Bus> inputs;
214
216 std::vector<Bus> outputs;
217
219 std::unordered_map<unsigned int, State> unconnectedInputDefaults;
220
223
226
229
231 uint64_t nextIoListenerId = 0;
232
234 std::unordered_map<uint64_t, IOObserver> ioListeners;
235
247 template <typename T>
248 void defineProperty(std::string key, T&& defaultValue,
249 PropertyCallback callback = nullptr)
250 {
252 if (callback) {
253 cb = std::move(callback);
254 propertyCallbacks[key] = cb;
255 }
256 using Decayed = std::decay_t<T>;
257 PropertyValue defaultVal;
258 if constexpr (std::is_constructible_v<std::string, T>
259 && !std::is_same_v<Decayed, bool>) {
260 defaultVal = std::string(std::forward<T>(defaultValue));
261 } else {
262 defaultVal = PropertyValue(std::forward<T>(defaultValue));
263 }
264 PropertyValue finalValue = cb ? cb(defaultVal) : std::move(defaultVal);
265 properties.insert_or_assign(std::move(key), std::move(finalValue));
266 }
267
276 void defineStringListProperty(std::string key, std::string defaultValue,
277 StringPropertyOptions allowedValues,
278 PropertyCallback callback = nullptr);
279
286 void notifyIOListeners();
287
289 void validatePropertyValue(std::string_view key, const PropertyValue& currentValue,
290 const PropertyValue& newValue) const;
291
298 void handleInputSizeChange(const unsigned int index, const unsigned int newSize);
299
306 template <typename Enum>
307 requires std::is_enum_v<Enum>
308 static constexpr unsigned int busIndex(Enum value)
309 {
310 return std::to_underlying(value);
311 }
312
318 void defineUnconnectedInputDefault(unsigned int input, State value)
319 {
320 unconnectedInputDefaults.insert_or_assign(input, value);
321 }
322
323 [[nodiscard]] State inputState(unsigned int input, unsigned short bit = 0) const
324 {
325 if (input < inputs.size() && bit < inputs[input].size() && inputs[input][bit])
326 return Wire::safeGetCurrentState(inputs[input][bit]);
327
328 return unconnectedInputDefault(input).value_or(State::ERROR);
329 }
330
331 [[nodiscard]] Wire_ptr inputWire(unsigned int input, unsigned short bit = 0) const
332 {
333 if (input >= inputs.size() || bit >= inputs[input].size())
334 return {};
335
336 return inputs[input][bit];
337 }
338
339 template <typename Enum>
340 requires std::is_enum_v<Enum>
341 [[nodiscard]] Wire_ptr inputWire(Enum input, unsigned short bit = 0) const
342 {
343 return inputWire(busIndex(input), bit);
344 }
345
353 template <typename Enum>
354 requires std::is_enum_v<Enum>
355 [[nodiscard]] State inputState(Enum input, unsigned short bit = 0) const
356 {
357 return inputState(busIndex(input), bit);
358 }
359
360 [[nodiscard]] Wire_ptr outputWire(unsigned int output, unsigned short bit = 0) const
361 {
362 if (output >= outputs.size() || bit >= outputs[output].size())
363 return {};
364
365 return outputs[output][bit];
366 }
367
375 template <typename Enum>
376 requires std::is_enum_v<Enum>
377 [[nodiscard]] Wire_ptr outputWire(Enum output, unsigned short bit = 0) const
378 {
379 return outputWire(busIndex(output), bit);
380 }
381
382 [[nodiscard]] std::size_t outputBusSize(unsigned int output) const
383 {
384 return output < outputs.size() ? outputs[output].size() : 0;
385 }
386
393 template <typename Enum>
394 requires std::is_enum_v<Enum>
395 [[nodiscard]] std::size_t outputBusSize(Enum output) const
396 {
397 return outputBusSize(busIndex(output));
398 }
399
400public:
401 Component() = default;
402
408 Component(std::vector<Bus> inputs, std::vector<Bus> outputs);
409
410 virtual ~Component() = default;
411
422 {
424 }
425
437 const SILICON::simulation::Context& context)
438 {
439 (void)context;
440 simulate(sim);
441 }
442
450 [[nodiscard]] virtual bool usesStagedSequentialOutputs() const { return false; }
451
459 void replaceBus(std::vector<Bus>& busCollection, unsigned int index, Bus newBus);
460
466 void setProperty(std::string_view key, const PropertyValue& value);
467
473 [[nodiscard]] std::optional<PropertyValue> getProperty(std::string_view key) const;
474
478 [[nodiscard]] const PropertyMap& getProperties() const { return properties; }
479
484 [[nodiscard]] std::optional<std::reference_wrapper<const StringPropertyOptions>>
485 getStringPropertyOptions(std::string_view key) const;
486
493 template <typename T> void setPropertyValue(std::string_view key, T&& value)
494 {
495 setProperty(key, PropertyValue(std::forward<T>(value)));
496 }
497
504 template <typename T> std::optional<T> getPropertyValue(std::string_view key) const
505 {
506 auto it = properties.find(key);
507 if (it != properties.end()) {
508 if (const T* val = std::get_if<T>(&it->second)) {
509 return *val;
510 }
511 }
512 return std::nullopt;
513 }
514
520 void setPropertyCallback(std::string_view key, PropertyCallback callback);
521
528 void setInput(unsigned int index, const Bus& bus, bool checkSize = false);
529
534 void setInputs(const std::vector<Bus>& newInputs);
535
541 void setOutput(unsigned int index, const Bus& bus);
542
547 void setOutputs(const std::vector<Bus>& newOutputs);
548
554 bool isConnectedTo(const Bus& b) const;
555
565 virtual void clearWires();
566
571 [[nodiscard]] std::vector<Bus> getInputs() const { return inputs; }
572
577 [[nodiscard]] const std::vector<Bus>& inputBuses() const { return inputs; }
578
584 [[nodiscard]] std::optional<State> unconnectedInputDefault(unsigned int input) const
585 {
586 if (const auto it = unconnectedInputDefaults.find(input);
587 it != unconnectedInputDefaults.end()) {
588 return it->second;
589 }
590 return std::nullopt;
591 }
592
597 [[nodiscard]] std::vector<Bus> getOutputs() const { return outputs; }
598
603 [[nodiscard]] const std::vector<Bus>& outputBuses() const { return outputs; }
604
609 [[nodiscard]] auto allBuses() const
610 {
611 return std::array{std::span<const Bus>(inputs), std::span<const Bus>(outputs)}
612 | std::views::join;
613 }
614
619 virtual std::string_view typeName() const = 0;
620
625 [[nodiscard]] virtual ComponentMetadata metadata() const;
626
633 virtual void serializeYosys(SILICON::yosys::SerializationContext& context) const;
634
635 // --- IO Observer Pattern ---
636
642 uint64_t addIOListener(IOObserver cb);
643
648 void removeIOListener(uint64_t id);
649};
650
651} // namespace SILICON::core
static constexpr unsigned int busIndex(Enum value)
Converts a component-local bus enum to its storage index.
Wire_ptr outputWire(unsigned int output, unsigned short bit=0) const
const std::vector< Bus > & inputBuses() const
Gets all input buses without copying.
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.
State inputState(unsigned int input, unsigned short bit=0) const
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.
const PropertyMap & getProperties() const
Gets all properties.
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::size_t outputBusSize(Enum output) const
Returns the size of an output bus, or zero when it is missing.
std::vector< Bus > getOutputs() const
Gets all output buses.
State inputState(Enum input, unsigned short bit=0) const
Reads an input bit, returning ERROR when the bus or bit is missing.
const std::vector< Bus > & outputBuses() const
Gets all output buses without copying.
void defineUnconnectedInputDefault(unsigned int input, State value)
Defines the state read from an input when its wire is unconnected.
std::unordered_map< unsigned int, State > unconnectedInputDefaults
Per-input state used when a bus bit has no connected wire.
std::vector< Bus > inputs
Input buses connected to this component.
std::optional< State > unconnectedInputDefault(unsigned int input) const
Gets the state used when an input has no connected wire.
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
virtual void simulate(SILICON::simulation::Simulator &sim, const SILICON::simulation::Context &context)
Executes the component's logic with simulator scheduling context.
virtual void simulate(SILICON::simulation::Simulator &sim)
Executes the component's logic.
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.
virtual ~Component()=default
Wire_ptr outputWire(Enum output, unsigned short bit=0) const
Returns an output wire, or null when the bus or bit is missing.
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
Wire_ptr inputWire(unsigned int input, unsigned short bit=0) const
uint64_t nextIoListenerId
Counter for generating unique I/O listener IDs.
virtual bool usesStagedSequentialOutputs() const
Whether zero-delay output writes should be staged during reactive passes.
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.
virtual void serializeYosys(SILICON::yosys::SerializationContext &context) const
Lower this component into native Yosys netlist cells.
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 setPropertyValue(std::string_view key, T &&value)
Sets a property value with type deduction.
void handleInputSizeChange(const unsigned int index, const unsigned int newSize)
Handles input size changes. By default input size shouldn't change automatically.
std::size_t outputBusSize(unsigned int output) const
Wire_ptr inputWire(Enum input, unsigned short bit=0) const
std::vector< Bus > getInputs() const
Gets all input buses.
void validatePropertyValue(std::string_view key, const PropertyValue &currentValue, const PropertyValue &newValue) const
Validates a property value against the declared type and metadata.
static State safeGetCurrentState(const std::weak_ptr< Wire > &w)
Definition wire.cpp:245
Executes event-driven simulation of a Circuit.
Definition simulator.hpp:74
Mutable module-building interface passed to component serializers.
Definition netlist.hpp:174
Concept to check if a type has a Type static member.
std::shared_ptr< Wire > Wire_ptr
Definition wire.hpp:116
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::unordered_map< std::string, PropertyValue, TransparentStringHash, TransparentStringEqual > PropertyMap
Map from property names to their values.
std::vector< std::string > StringPropertyOptions
Allowed values for a constrained string property.
PortRole
Declares whether a component represents a public circuit boundary port.
Definition component.hpp:66
std::unordered_map< std::string, PropertyCallback, TransparentStringHash, TransparentStringEqual > PropertyCallbackMap
Map from property names to their callback functions.
std::unordered_map< std::string, StringPropertyOptions, TransparentStringHash, TransparentStringEqual > StringPropertyOptionsMap
Map from property names to constrained string values.
Transparent equality functor for string-like keys.
Transparent hash functor for string-like keys.
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.
std::unordered_map< uint64_t, core::State > previousWireStates
Wire states captured before the reactive mutation that caused this pass.
Definition component.hpp:98
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