Skip to content

netlist_carpentry.utils.gate_lib

The gate_lib module provides a library of digital gates and other netlist elements.

These gates are the basic building blocks of digital circuits, and they can be combined to create more complex circuits. The module includes classes for various types of gates, including unary gates (such as buffers and inverters), binary gates (such as AND, OR, and XOR gates), and more complex gates like multiplexers and demultiplexers.

Every primitive gate from this library has an instance_type string, which starts with an {CFG.nc_identifier_internal} (section symbol), which is not a valid Verilog symbol for use in identifiers (except if escaped). This is intended to distinguish primitive gates from user-defined module instances.

Classes:

  • Buffer

    A buffer gate.

  • NotGate

    An inverter gate.

  • PosGate

    An arithmetic plus gate.

  • NegGate

    An arithmetic negator gate.

  • ReduceAnd

    A reduction AND gate.

  • ReduceOr

    A reduction OR gate.

  • ReduceBool

    A reduction Boolean gate.

  • ReduceXor

    A reduction XOR gate.

  • ReduceXnor

    A reduction XNOR gate.

  • LogicNot

    A logic not gate.

  • AndGate

    An AND gate.

  • OrGate

    An OR gate.

  • XorGate

    An XOR gate.

  • XnorGate

    An XNOR gate.

  • NorGate

    A NOR gate.

  • NandGate

    A NAND gate.

  • BitwiseCaseEquality

    A BITWISE CASE EQUALITY gate.

  • ShiftSigned

    A signed SHIFT gate.

  • ShiftLeft

    A SHIFT-LEFT gate.

  • ShiftRight

    A SHIFT-RIGHT gate.

  • ArithmeticShiftLeft

    An ARITHMETIC SHIFT-LEFT gate.

  • ArithmeticShiftRight

    An ARITHMETIC SHIFT-RIGHT gate.

  • ShiftX

    A SHIFT-X gate.

  • LogicAnd

    A LOGIC-AND gate.

  • LogicOr

    A LOGIC-OR gate.

  • LessThan

    A LESS-THAN gate.

  • LessEqual

    A LESS-OR-EQUAL gate.

  • Equal

    An EQUAL gate.

  • CaseEqual

    A CASE-EQUAL gate.

  • NotEqual

    A NOT-EQUAL gate.

  • CaseNotEqual

    A CASE-NOT-EQUAL gate.

  • GreaterThan

    A GREATER-THAN gate.

  • GreaterEqual

    A GREATER-OR-EQUAL gate.

  • Multiplexer

    A multiplexer.

  • Demultiplexer

    A demultiplexer.

  • Exponentiator
  • DFF

    A D flip-flop (DFF) is a clocked gate that stores a value on its input port and outputs it on its output port.

  • ADFF

    Asynchronously resettable DFF.

  • DFFE

    DFF with enable port.

  • ADFFE

    Asynchronously resettable DFF with enable port.

  • SDFF

    Synchronously resettable DFF.

  • SDFFCE

    Synchronously resettable DFF with enable port, where the enable signal takes precedence over the reset signal.

  • SDFFE

    Synchronously resettable DFF with enable port, where the reset signal takes precedence over the enable signal.

  • ALDFF

    Asynchronously load DFF, with a load-enable (AL) and load-data (AD) port.

  • ALDFFE

    Asynchronously load DFF, with a load-enable (AL) and load-data (AD) port and an additional enable port for the default case.

  • DFFSRE

Functions:

  • get

    Retrieves the class of a primitive gate based on its instance type.

Buffer

Bases: UnaryGate, BaseModel

A buffer gate.

A buffer gate is a gate that simply passes its input signal to its output. It is used to isolate a signal or to drive a long wire.

Methods:

  • change_mutability

    Change the mutability status of this instance and optionally its ports.

  • evaluate

    Evaluates the gate's output signal based on its input signals.

  • all_connections

    Returns a dictionary mapping port names to their corresponding connection paths.

  • model_post_init

    Initializes the gate's ports and connections.

  • connect

    Add connections to the specified port of this instance.

  • disconnect

    Remove an existing connection from a specified port of this instance.

  • get_connection

    Retrieve the connection path associated with a specified port and bit index.

  • modify_connection

    Modify an existing connection within a specified port of this instance.

  • connect_modify

    Add a new connection or modify an existing one within the specified port of this instance.

  • tie_port

    Set a constant signal value for the specified port and bit index.

  • has_tied_ports

    Checks the ports of this instance whether any are tied to constant values.

  • has_tied_inputs

    Checks the input ports of this instance whether any are tied to constant values.

  • has_tied_outputs

    Checks the output ports of this instance whether any are tied to constant values.

  • update_signedness

    Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

  • split

    Performs a bit-wise split on this instance.

  • p2v

    Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

  • ps2v

    Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

  • set

    Sets the signal on a port.

  • get_result_vector

    Returns the result of this gate's operation for a full signal vector.

  • signal_in

    The input signal of the gate.

  • signal_out

    The output signal of the gate.

Attributes:

name instance-attribute

name: str

The name of the element.

!!! Do not modify this variable after instantiating it. Use NetlistElement.set_name() instead. Modifying this variable might lead to inconsistencies later on.

metadata class-attribute instance-attribute

Metadata of a netlist element.

Can be user-defined, or e. g. by Yosys (such as src for the HDL source). Is also grouped by categories, i.e. all metadata from Yosys can be accessed via Module.metadata["yosys"], or via Module.metadata.yosys, which both return a dictionary of all metadata. Read the documentation of MetaDataMixin for more information.

path property

Returns the InstancePath of the netlist element.

The InstancePath object is constructed using the element's type and its raw hierarchical path.

Returns:

  • InstancePath ( InstancePath ) –

    The hierarchical path of the netlist element.

type property

type: EType

The type of the element, which is an instance.

hierarchy_level property

hierarchy_level: int

The level of hierarchy of the element in the design.

The hierarchy level is the number of separators in the element's raw path. For example, a top-level instance has a hierarchy level of 0, while a direct submodule instance has a hierarchy level of 1.

Returns:

  • int ( int ) –

    The hierarchy level of the element.

has_parent property

has_parent: bool

Whether this object has a parent.

circuit property

circuit: 'Circuit'

The circuit object to which this netlist element belongs to.

  • For a module, returns the circuit to which the module belongs.
  • For any other netlist element, recursively returns the circuit of the parent, which ultimately leads to a module, to which the netlist element belongs.

Raises:

  • ParentNotFoundError

    If a parent cannot be resolved somewhere in the hierarchical chain.

  • ObjectNotFoundError

    If for a module no circuit is set.

has_circuit property

has_circuit: bool

Whether this netlist element has a defined circuit it belongs to.

Tries to access self.circuit and returns whether the call was successful. Can be used instead of a try-except clause around the call to NetlistElement.circuit.

locked property

locked: bool

True if this NetlistElement instance is locked (i.e. it is currently structurally unchangeable), False if it is mutable.

Can be changed via NetlistElement.change_mutability(bool).

Immutability is used to prevent accidental changes to the design.

is_placeholder_instance property

is_placeholder_instance: bool

A placeholder represents an element that does not have a specific path.

True if this NetlistElement instance represents a placeholder, False otherwise.

can_carry_signal property

can_carry_signal: bool

Whether this exact object is able to receive, pass or hold signal values.

True for ports (as they drive or receive values) and wires (as they pass the signals from driver to load ports) as well as their respective segments. False for instances and modules.

connections property

connections: Dict[str, Dict[int, WireSegmentPath]]

A dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port. Elements with no connection (i.e. the path is None) are excluded. In case these are needed, use Instance.get_connections() instead.

Example

{ 'port1': {1: WireSegmentPath('path/to/element1'), 2: WireSegmentPath('path/to/element2')}, 'port2': {1: WireSegmentPath('path/to/element3')} }

connection_str_paths property

connection_str_paths: Dict[str, Dict[int, str]]

Returns a dictionary mapping port names to their corresponding connection paths as strings.

The keys are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are the raw string paths.

Example

{ 'port1': {0: 'path.to.element1', 1: 'path.to.element2'}, 'port2': {0: 'path.to.element3'} }

ports property

A dictionary mapping port names to their corresponding Port objects.

The keys of the dictionary are the names of the ports. The values are Port objects representing the ports.

Returns:

input_ports property

input_ports: Tuple[Port[Instance], ...]

Returns a tuple of input ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as inputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the input ports.

output_ports property

output_ports: Tuple[Port[Instance], ...]

Returns a tuple of output ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as outputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the output ports.

has_unconnected_port_segments property

has_unconnected_port_segments: bool

Returns True if the instance has at least one unconnected port segment.

signals property

signals: Dict[str, SignalArray]

A dictionary with all signals currently present on all ports of this instance.

is_blackbox property

is_blackbox: bool

Flag indicating whether the instance represents neither a primitive element nor a module instance.

If True, this instance does not have a module definition, and is also not a basic component (i.e. a primitive gate instance) from the internal gate library, such as a gate or flip-flop.

y_width property

y_width: PositiveInt

Width of the gate, based on a certain port's width, depending on the actual gate.

a_width property

a_width: PositiveInt

Width of the gate's A port.

b_width property

b_width: PositiveInt

Width of the gate's B port.

is_combinational property

is_combinational: bool

Whether instances of this gate are considered combinational gates.

True for combinational gates, such as AND gates or arithmetic gates. False for flip-flops and latches.

is_sequential property

is_sequential: bool

Whether instances of this gate are considered sequential gates.

False for combinational gates, such as AND gates or arithmetic gates. True for flip-flops and latches.

output_port property

output_port: Port[Instance]

The output port of the gate.

data_width property

data_width: int

The data width of this instance.

Defaults to the data width of the output port. Can be overwritten in extended classes.

In contrast to self.width, which is used for the creation and initialization, this property is linked to the data width of the output port. This property is useful when the data width of the output port can be changed.

input_port property

input_port: Port[Instance]

The input port of the gate.

a_signed property

a_signed: bool

The signedness of input port A.

truth_table property

truth_table: Dict[Signal, Signal]

A simple truth table as a dictionary.

This dictionary contains the input-output mapping for unary gates that evaluate bitwise (e.g. Buffer, NotGate). Not implemented for arithmetic gates (e.g. NegGate, PosGate).

change_mutability

change_mutability(is_now_locked: bool, recursive: bool = False) -> Self

Change the mutability status of this instance and optionally its ports.

This method allows setting whether this instance can be modified or not. If recursive is set to True, it also applies the same mutability status to all ports of this instance.

Parameters:

  • is_now_locked

    (bool) –

    The new mutability status for this instance.

  • recursive

    (bool, default: False ) –

    Whether to apply the change recursively to its ports. Defaults to False.

evaluate

evaluate() -> None

Evaluates the gate's output signal based on its input signals.

This method is called when the gate's input signals change, and it updates the gate's output signal accordingly.

all_connections

all_connections(
    include_unconnected: bool,
) -> Dict[str, Dict[int, WireSegmentPath]]

Returns a dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port.

Parameters:

  • include_unconnected

    (bool) –

    Whether to include unconnected ports in the result.

Returns:

model_post_init

model_post_init(__context: object) -> None

Initializes the gate's ports and connections.

This method is called after the gate's attributes have been initialized, and it sets up the gate's ports and connections.

connect

connect(
    port_name: str,
    ws_path: Optional[WireSegmentPath],
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add connections to the specified port of this instance.

This method can establish multiple connections if a range of indices is provided.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection(s) should be established.

  • ws_path

    (Optional[WireSegmentPath]) –

    The path of the wire segment that will be connected to this port. If None, the associated port (segment) remains unconnected.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

Raises:

  • ObjectLockedError

    If this instance is currently locked, and no connection can be made.

disconnect

disconnect(port_name: str, index: Optional[int] = None) -> None

Remove an existing connection from a specified port of this instance.

This method disconnects the wire segment at the given index within the specified port_name.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be removed.

  • index

    (Optional[int], default: None ) –

    The bit index within the port for this disconnection. Defaults to None, which completely disconnects the port.

Raises:

get_connection

get_connection(
    port_name: str, index: Optional[NonNegativeInt] = None
) -> Union[WireSegmentPath, Dict[int, WireSegmentPath], None]

Retrieve the connection path associated with a specified port and bit index.

If index is provided, this method returns the wire segment path connected to that specific bit within the port. Otherwise, it returns all connections for the given port as a dictionary mapping indices to WireSegmentPaths.

Parameters:

  • port_name

    (str) –

    The name of the port for which to retrieve the connection(s).

  • index

    (Optional[NonNegativeInt], default: None ) –

    The bit index within the port. Defaults to None.

Returns:

modify_connection

modify_connection(
    port_name: str, ws_path: WireSegmentPath, index: NonNegativeInt = 0
) -> None

Modify an existing connection within a specified port of this instance.

This method updates the wire segment path at the given index within the specified port_name. If the index does not exist yet, it is newly added, changing the width of the port.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be modified.

  • ws_path

    (WireSegmentPath) –

    The new wire segment path for this connection.

  • index

    (NonNegativeInt, default: 0 ) –

    The bit index within the port. Defaults to 0.

connect_modify

connect_modify(
    port_name: str,
    ws_path: WireSegmentPath,
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add a new connection or modify an existing one within the specified port of this instance.

If the connection already exists at the given index and port_name, it will be modified. Otherwise, a new connection is added.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be established or updated.

  • ws_path

    (WireSegmentPath) –

    The path of the wire segment that will be connected to this port.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

tie_port

tie_port(name: str, index: NonNegativeInt, sig_value: LogicLevel) -> None

Set a constant signal value for the specified port and bit index.

If the specified port does not exist, an error message is logged and the function returns False. Otherwise, the method tries to set the constant signal value for that port and returns True if successful.

Does not work for instance output ports, as they are always driven by their parent instances.

Parameters:

  • name

    (str) –

    The name of the port.

  • index

    (NonNegativeInt) –

    The bit index within the port.

  • sig_value

    (LogicLevel) –

    The constant signal value to be set ('0', '1', or 'Z').

Raises:

  • ObjectNotFoundError

    If no such port or port segment exists.

  • AlreadyConnectedError

    (raised by: PortSegment.tie_signal) If this segment is belongs to a load port and is already connected to a wire, from which it receives its value.

  • InvalidDirectionError

    (raised by: PortSegment.tie_signal) If this port segment belongs to an instance output port, which is driven by the instance inputs and the instance's internal logic.

  • InvalidSignalError

    (raised by: PortSegment.tie_signal) If an invalid value is provided.

has_tied_ports

has_tied_ports() -> bool

Checks the ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any ports of this instance are tied to constant values. False otherwise, i.e. all ports are connected to wires.

has_tied_inputs

has_tied_inputs() -> bool

Checks the input ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any input ports of this instance are tied to constant values. False otherwise, i.e. all input ports are connected to wires.

has_tied_outputs

has_tied_outputs() -> bool

Checks the output ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any output ports of this instance are tied to constant values. False otherwise, i.e. all output ports are connected to wires.

update_signedness

update_signedness(port_name: str) -> None

Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

Parameters:

  • port_name

    (str) –

    The name of the port, of which the signedness value is retrieved.

split

split() -> Dict[NonNegativeInt, Self]

Performs a bit-wise split on this instance.

If this instance supports splitting and has a data width of n bit, this method splits this instance into n 1-bit instances. This works for instances, where each output bit depends only on the corresponding input bit(s), e.g. an AND gate or a D-Flipflop.

Returns:

  • Dict[NonNegativeInt, Self]

    Dict[int, Instance]: An n-bit large dictionary, where each key conforms to a bit of the original instance, and each value is an 1-bit instance representing the corresponding "slice" of the original instance.

Raises:

  • SplittingUnsupportedError

    If this instance does not support splitting. Happens for any gate or instance whose behavior depends on the whole bus, and splitting would make it lose its meaning.

p2v

p2v(
    port: ANY_PORT,
    exclude_indices: Optional[List[int]] = None,
    include_indices: Optional[List[int]] = None,
) -> str

Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a Port object and converts them to their corresponding Verilog signal structure (p2v -> Port to Verilog signal syntax). For each segment of the port, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port is set to a constant, the corresponding constant wire segment placeholder is used instead. Port segments can be excluded from the conversion by providing a list of indices to the exclude_indices parameter, indicating which segments should be excluded from the conversion (e.g. segments that are known to be unconnected). Vice versa, only a certain subset of the port's segments may be converted to Verilog syntax, if include_indices is a given list of port indices. All indices not present in the list will be excluded from the conversion.

Parameters:

  • port

    (Port) –

    The Port object to convert.

  • exclude_indices

    (List[int], default: None ) –

    A list of indices to exclude from the conversion. Defaults to None.

  • include_indices

    (List[int], default: None ) –

    A list of indices (i.e. port slices) to include only for the conversion. Defaults to None.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

  • ObjectNotFoundError

    If the wire connected to a certain port segment could not be found.

  • UnsupportedOperationError

    If both exclude_indices and include_indices are specified. Only one of both may be given when calling this method.

ps2v

Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a PortSegment dictionary and converts them to their corresponding Verilog signal structure (ps2v -> PortSegment to Verilog signal syntax). For each segment, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port segment is set to a constant, the corresponding constant wire segment placeholder is used instead.

Parameters:

  • ps_dict

    (Dict[int, PortSegment]) –

    The PortSegment dictionary to convert. Each key (int) conforms to the index of the associated PortSegment object.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

set

set(
    port_name: str,
    new_signal: SignalOrLogicLevel,
    idx: Union[int, List[int]] = 0,
) -> None

Sets the signal on a port.

Parameters:

  • port_name

    (str) –

    The name of the port to set the signal on.

  • new_signal

    (Signal) –

    The new signal value.

  • idx

    (Union[int, List[int]], default: 0 ) –

    The index (or indices) to apply the given signal to. Can either be an integer (single index to set) or an iterable of integers (e.g. a list of indices). For every integer of the iterable the signal value of the corresponding port index is set to the given new_signal. Defaults to 0.

Example

from netlist_carpentry.utils.gate_factory import and_gate module = Module(name='m') a = module.create_port('a', 'input', width=6) instance = and_gate(module, 'inst', A=a)

This sets the value of bit 0 of port A to HIGH

instance.set('A', 1, 0) instance.ports['A'].signal_str 'xxxxx1'

This sets the value of bits 1, 3 and 5 of port A to LOW, leaving the other bits as they already are.

instance.set('A', 0, [1, 3, 5]) instance.ports['A'].signal_str '0x0x01'

get_result_vector

get_result_vector(s: SignalArray) -> SignalArray

Returns the result of this gate's operation for a full signal vector.

This method provides a unified interface for all unary gates to operate on :class:SignalArray (multi-bit) inputs. The default implementation iterates over each bit index and calls :meth:get_result for bitwise gates (e.g. Buffer, NotGate). Gates that operate on the full vector (e.g. arithmetic gates like PosGate, NegGate) override this method with their vector-level logic.

For reduction gates (e.g. ReduceAnd, ReduceOr), the output is a 1-bit :class:SignalArray regardless of input width.

Parameters:

Returns:

  • SignalArray ( SignalArray ) –

    The result of this gate's operation on the given signals. For bitwise gates, this has the same width as the input. For reduction gates, this is a 1-bit SignalArray.

signal_in

signal_in(idx: NonNegativeInt = 0) -> Signal

The input signal of the gate.

Returns:

  • Signal ( Signal ) –

    The input signal of the gate.

signal_out

signal_out(idx: NonNegativeInt = 0) -> Signal

The output signal of the gate.

Returns:

  • Signal ( Signal ) –

    The output signal of the gate.

NotGate

Bases: UnaryGate, BaseModel

An inverter gate.

An inverter gate is a gate that inverts its input signal. It produces a HIGH output signal if its input signal is LOW, and vice versa.

Methods:

  • change_mutability

    Change the mutability status of this instance and optionally its ports.

  • evaluate

    Evaluates the gate's output signal based on its input signals.

  • all_connections

    Returns a dictionary mapping port names to their corresponding connection paths.

  • model_post_init

    Initializes the gate's ports and connections.

  • connect

    Add connections to the specified port of this instance.

  • disconnect

    Remove an existing connection from a specified port of this instance.

  • get_connection

    Retrieve the connection path associated with a specified port and bit index.

  • modify_connection

    Modify an existing connection within a specified port of this instance.

  • connect_modify

    Add a new connection or modify an existing one within the specified port of this instance.

  • tie_port

    Set a constant signal value for the specified port and bit index.

  • has_tied_ports

    Checks the ports of this instance whether any are tied to constant values.

  • has_tied_inputs

    Checks the input ports of this instance whether any are tied to constant values.

  • has_tied_outputs

    Checks the output ports of this instance whether any are tied to constant values.

  • update_signedness

    Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

  • split

    Performs a bit-wise split on this instance.

  • p2v

    Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

  • ps2v

    Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

  • set

    Sets the signal on a port.

  • get_result_vector

    Returns the result of this gate's operation for a full signal vector.

  • signal_in

    The input signal of the gate.

  • signal_out

    The output signal of the gate.

Attributes:

name instance-attribute

name: str

The name of the element.

!!! Do not modify this variable after instantiating it. Use NetlistElement.set_name() instead. Modifying this variable might lead to inconsistencies later on.

metadata class-attribute instance-attribute

Metadata of a netlist element.

Can be user-defined, or e. g. by Yosys (such as src for the HDL source). Is also grouped by categories, i.e. all metadata from Yosys can be accessed via Module.metadata["yosys"], or via Module.metadata.yosys, which both return a dictionary of all metadata. Read the documentation of MetaDataMixin for more information.

path property

Returns the InstancePath of the netlist element.

The InstancePath object is constructed using the element's type and its raw hierarchical path.

Returns:

  • InstancePath ( InstancePath ) –

    The hierarchical path of the netlist element.

type property

type: EType

The type of the element, which is an instance.

hierarchy_level property

hierarchy_level: int

The level of hierarchy of the element in the design.

The hierarchy level is the number of separators in the element's raw path. For example, a top-level instance has a hierarchy level of 0, while a direct submodule instance has a hierarchy level of 1.

Returns:

  • int ( int ) –

    The hierarchy level of the element.

has_parent property

has_parent: bool

Whether this object has a parent.

circuit property

circuit: 'Circuit'

The circuit object to which this netlist element belongs to.

  • For a module, returns the circuit to which the module belongs.
  • For any other netlist element, recursively returns the circuit of the parent, which ultimately leads to a module, to which the netlist element belongs.

Raises:

  • ParentNotFoundError

    If a parent cannot be resolved somewhere in the hierarchical chain.

  • ObjectNotFoundError

    If for a module no circuit is set.

has_circuit property

has_circuit: bool

Whether this netlist element has a defined circuit it belongs to.

Tries to access self.circuit and returns whether the call was successful. Can be used instead of a try-except clause around the call to NetlistElement.circuit.

locked property

locked: bool

True if this NetlistElement instance is locked (i.e. it is currently structurally unchangeable), False if it is mutable.

Can be changed via NetlistElement.change_mutability(bool).

Immutability is used to prevent accidental changes to the design.

is_placeholder_instance property

is_placeholder_instance: bool

A placeholder represents an element that does not have a specific path.

True if this NetlistElement instance represents a placeholder, False otherwise.

can_carry_signal property

can_carry_signal: bool

Whether this exact object is able to receive, pass or hold signal values.

True for ports (as they drive or receive values) and wires (as they pass the signals from driver to load ports) as well as their respective segments. False for instances and modules.

connections property

connections: Dict[str, Dict[int, WireSegmentPath]]

A dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port. Elements with no connection (i.e. the path is None) are excluded. In case these are needed, use Instance.get_connections() instead.

Example

{ 'port1': {1: WireSegmentPath('path/to/element1'), 2: WireSegmentPath('path/to/element2')}, 'port2': {1: WireSegmentPath('path/to/element3')} }

connection_str_paths property

connection_str_paths: Dict[str, Dict[int, str]]

Returns a dictionary mapping port names to their corresponding connection paths as strings.

The keys are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are the raw string paths.

Example

{ 'port1': {0: 'path.to.element1', 1: 'path.to.element2'}, 'port2': {0: 'path.to.element3'} }

ports property

A dictionary mapping port names to their corresponding Port objects.

The keys of the dictionary are the names of the ports. The values are Port objects representing the ports.

Returns:

input_ports property

input_ports: Tuple[Port[Instance], ...]

Returns a tuple of input ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as inputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the input ports.

output_ports property

output_ports: Tuple[Port[Instance], ...]

Returns a tuple of output ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as outputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the output ports.

has_unconnected_port_segments property

has_unconnected_port_segments: bool

Returns True if the instance has at least one unconnected port segment.

signals property

signals: Dict[str, SignalArray]

A dictionary with all signals currently present on all ports of this instance.

is_blackbox property

is_blackbox: bool

Flag indicating whether the instance represents neither a primitive element nor a module instance.

If True, this instance does not have a module definition, and is also not a basic component (i.e. a primitive gate instance) from the internal gate library, such as a gate or flip-flop.

y_width property

y_width: PositiveInt

Width of the gate, based on a certain port's width, depending on the actual gate.

a_width property

a_width: PositiveInt

Width of the gate's A port.

b_width property

b_width: PositiveInt

Width of the gate's B port.

is_combinational property

is_combinational: bool

Whether instances of this gate are considered combinational gates.

True for combinational gates, such as AND gates or arithmetic gates. False for flip-flops and latches.

is_sequential property

is_sequential: bool

Whether instances of this gate are considered sequential gates.

False for combinational gates, such as AND gates or arithmetic gates. True for flip-flops and latches.

output_port property

output_port: Port[Instance]

The output port of the gate.

data_width property

data_width: int

The data width of this instance.

Defaults to the data width of the output port. Can be overwritten in extended classes.

In contrast to self.width, which is used for the creation and initialization, this property is linked to the data width of the output port. This property is useful when the data width of the output port can be changed.

input_port property

input_port: Port[Instance]

The input port of the gate.

a_signed property

a_signed: bool

The signedness of input port A.

truth_table property

truth_table: Dict[Signal, Signal]

A simple truth table as a dictionary.

This dictionary contains the input-output mapping for unary gates that evaluate bitwise (e.g. Buffer, NotGate). Not implemented for arithmetic gates (e.g. NegGate, PosGate).

change_mutability

change_mutability(is_now_locked: bool, recursive: bool = False) -> Self

Change the mutability status of this instance and optionally its ports.

This method allows setting whether this instance can be modified or not. If recursive is set to True, it also applies the same mutability status to all ports of this instance.

Parameters:

  • is_now_locked

    (bool) –

    The new mutability status for this instance.

  • recursive

    (bool, default: False ) –

    Whether to apply the change recursively to its ports. Defaults to False.

evaluate

evaluate() -> None

Evaluates the gate's output signal based on its input signals.

This method is called when the gate's input signals change, and it updates the gate's output signal accordingly.

all_connections

all_connections(
    include_unconnected: bool,
) -> Dict[str, Dict[int, WireSegmentPath]]

Returns a dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port.

Parameters:

  • include_unconnected

    (bool) –

    Whether to include unconnected ports in the result.

Returns:

model_post_init

model_post_init(__context: object) -> None

Initializes the gate's ports and connections.

This method is called after the gate's attributes have been initialized, and it sets up the gate's ports and connections.

connect

connect(
    port_name: str,
    ws_path: Optional[WireSegmentPath],
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add connections to the specified port of this instance.

This method can establish multiple connections if a range of indices is provided.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection(s) should be established.

  • ws_path

    (Optional[WireSegmentPath]) –

    The path of the wire segment that will be connected to this port. If None, the associated port (segment) remains unconnected.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

Raises:

  • ObjectLockedError

    If this instance is currently locked, and no connection can be made.

disconnect

disconnect(port_name: str, index: Optional[int] = None) -> None

Remove an existing connection from a specified port of this instance.

This method disconnects the wire segment at the given index within the specified port_name.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be removed.

  • index

    (Optional[int], default: None ) –

    The bit index within the port for this disconnection. Defaults to None, which completely disconnects the port.

Raises:

get_connection

get_connection(
    port_name: str, index: Optional[NonNegativeInt] = None
) -> Union[WireSegmentPath, Dict[int, WireSegmentPath], None]

Retrieve the connection path associated with a specified port and bit index.

If index is provided, this method returns the wire segment path connected to that specific bit within the port. Otherwise, it returns all connections for the given port as a dictionary mapping indices to WireSegmentPaths.

Parameters:

  • port_name

    (str) –

    The name of the port for which to retrieve the connection(s).

  • index

    (Optional[NonNegativeInt], default: None ) –

    The bit index within the port. Defaults to None.

Returns:

modify_connection

modify_connection(
    port_name: str, ws_path: WireSegmentPath, index: NonNegativeInt = 0
) -> None

Modify an existing connection within a specified port of this instance.

This method updates the wire segment path at the given index within the specified port_name. If the index does not exist yet, it is newly added, changing the width of the port.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be modified.

  • ws_path

    (WireSegmentPath) –

    The new wire segment path for this connection.

  • index

    (NonNegativeInt, default: 0 ) –

    The bit index within the port. Defaults to 0.

connect_modify

connect_modify(
    port_name: str,
    ws_path: WireSegmentPath,
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add a new connection or modify an existing one within the specified port of this instance.

If the connection already exists at the given index and port_name, it will be modified. Otherwise, a new connection is added.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be established or updated.

  • ws_path

    (WireSegmentPath) –

    The path of the wire segment that will be connected to this port.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

tie_port

tie_port(name: str, index: NonNegativeInt, sig_value: LogicLevel) -> None

Set a constant signal value for the specified port and bit index.

If the specified port does not exist, an error message is logged and the function returns False. Otherwise, the method tries to set the constant signal value for that port and returns True if successful.

Does not work for instance output ports, as they are always driven by their parent instances.

Parameters:

  • name

    (str) –

    The name of the port.

  • index

    (NonNegativeInt) –

    The bit index within the port.

  • sig_value

    (LogicLevel) –

    The constant signal value to be set ('0', '1', or 'Z').

Raises:

  • ObjectNotFoundError

    If no such port or port segment exists.

  • AlreadyConnectedError

    (raised by: PortSegment.tie_signal) If this segment is belongs to a load port and is already connected to a wire, from which it receives its value.

  • InvalidDirectionError

    (raised by: PortSegment.tie_signal) If this port segment belongs to an instance output port, which is driven by the instance inputs and the instance's internal logic.

  • InvalidSignalError

    (raised by: PortSegment.tie_signal) If an invalid value is provided.

has_tied_ports

has_tied_ports() -> bool

Checks the ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any ports of this instance are tied to constant values. False otherwise, i.e. all ports are connected to wires.

has_tied_inputs

has_tied_inputs() -> bool

Checks the input ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any input ports of this instance are tied to constant values. False otherwise, i.e. all input ports are connected to wires.

has_tied_outputs

has_tied_outputs() -> bool

Checks the output ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any output ports of this instance are tied to constant values. False otherwise, i.e. all output ports are connected to wires.

update_signedness

update_signedness(port_name: str) -> None

Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

Parameters:

  • port_name

    (str) –

    The name of the port, of which the signedness value is retrieved.

split

split() -> Dict[NonNegativeInt, Self]

Performs a bit-wise split on this instance.

If this instance supports splitting and has a data width of n bit, this method splits this instance into n 1-bit instances. This works for instances, where each output bit depends only on the corresponding input bit(s), e.g. an AND gate or a D-Flipflop.

Returns:

  • Dict[NonNegativeInt, Self]

    Dict[int, Instance]: An n-bit large dictionary, where each key conforms to a bit of the original instance, and each value is an 1-bit instance representing the corresponding "slice" of the original instance.

Raises:

  • SplittingUnsupportedError

    If this instance does not support splitting. Happens for any gate or instance whose behavior depends on the whole bus, and splitting would make it lose its meaning.

p2v

p2v(
    port: ANY_PORT,
    exclude_indices: Optional[List[int]] = None,
    include_indices: Optional[List[int]] = None,
) -> str

Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a Port object and converts them to their corresponding Verilog signal structure (p2v -> Port to Verilog signal syntax). For each segment of the port, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port is set to a constant, the corresponding constant wire segment placeholder is used instead. Port segments can be excluded from the conversion by providing a list of indices to the exclude_indices parameter, indicating which segments should be excluded from the conversion (e.g. segments that are known to be unconnected). Vice versa, only a certain subset of the port's segments may be converted to Verilog syntax, if include_indices is a given list of port indices. All indices not present in the list will be excluded from the conversion.

Parameters:

  • port

    (Port) –

    The Port object to convert.

  • exclude_indices

    (List[int], default: None ) –

    A list of indices to exclude from the conversion. Defaults to None.

  • include_indices

    (List[int], default: None ) –

    A list of indices (i.e. port slices) to include only for the conversion. Defaults to None.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

  • ObjectNotFoundError

    If the wire connected to a certain port segment could not be found.

  • UnsupportedOperationError

    If both exclude_indices and include_indices are specified. Only one of both may be given when calling this method.

ps2v

Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a PortSegment dictionary and converts them to their corresponding Verilog signal structure (ps2v -> PortSegment to Verilog signal syntax). For each segment, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port segment is set to a constant, the corresponding constant wire segment placeholder is used instead.

Parameters:

  • ps_dict

    (Dict[int, PortSegment]) –

    The PortSegment dictionary to convert. Each key (int) conforms to the index of the associated PortSegment object.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

set

set(
    port_name: str,
    new_signal: SignalOrLogicLevel,
    idx: Union[int, List[int]] = 0,
) -> None

Sets the signal on a port.

Parameters:

  • port_name

    (str) –

    The name of the port to set the signal on.

  • new_signal

    (Signal) –

    The new signal value.

  • idx

    (Union[int, List[int]], default: 0 ) –

    The index (or indices) to apply the given signal to. Can either be an integer (single index to set) or an iterable of integers (e.g. a list of indices). For every integer of the iterable the signal value of the corresponding port index is set to the given new_signal. Defaults to 0.

Example

from netlist_carpentry.utils.gate_factory import and_gate module = Module(name='m') a = module.create_port('a', 'input', width=6) instance = and_gate(module, 'inst', A=a)

This sets the value of bit 0 of port A to HIGH

instance.set('A', 1, 0) instance.ports['A'].signal_str 'xxxxx1'

This sets the value of bits 1, 3 and 5 of port A to LOW, leaving the other bits as they already are.

instance.set('A', 0, [1, 3, 5]) instance.ports['A'].signal_str '0x0x01'

get_result_vector

get_result_vector(s: SignalArray) -> SignalArray

Returns the result of this gate's operation for a full signal vector.

This method provides a unified interface for all unary gates to operate on :class:SignalArray (multi-bit) inputs. The default implementation iterates over each bit index and calls :meth:get_result for bitwise gates (e.g. Buffer, NotGate). Gates that operate on the full vector (e.g. arithmetic gates like PosGate, NegGate) override this method with their vector-level logic.

For reduction gates (e.g. ReduceAnd, ReduceOr), the output is a 1-bit :class:SignalArray regardless of input width.

Parameters:

Returns:

  • SignalArray ( SignalArray ) –

    The result of this gate's operation on the given signals. For bitwise gates, this has the same width as the input. For reduction gates, this is a 1-bit SignalArray.

signal_in

signal_in(idx: NonNegativeInt = 0) -> Signal

The input signal of the gate.

Returns:

  • Signal ( Signal ) –

    The input signal of the gate.

signal_out

signal_out(idx: NonNegativeInt = 0) -> Signal

The output signal of the gate.

Returns:

  • Signal ( Signal ) –

    The output signal of the gate.

PosGate

Bases: UnaryGate, BaseModel

An arithmetic plus gate.

An arithmetic plus gate is a gate that just returns its input signal, sign extended.

Methods:

  • change_mutability

    Change the mutability status of this instance and optionally its ports.

  • evaluate

    Evaluates the gate's output signal based on its input signals.

  • all_connections

    Returns a dictionary mapping port names to their corresponding connection paths.

  • model_post_init

    Initializes the gate's ports and connections.

  • connect

    Add connections to the specified port of this instance.

  • disconnect

    Remove an existing connection from a specified port of this instance.

  • get_connection

    Retrieve the connection path associated with a specified port and bit index.

  • modify_connection

    Modify an existing connection within a specified port of this instance.

  • connect_modify

    Add a new connection or modify an existing one within the specified port of this instance.

  • tie_port

    Set a constant signal value for the specified port and bit index.

  • has_tied_ports

    Checks the ports of this instance whether any are tied to constant values.

  • has_tied_inputs

    Checks the input ports of this instance whether any are tied to constant values.

  • has_tied_outputs

    Checks the output ports of this instance whether any are tied to constant values.

  • update_signedness

    Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

  • split

    Performs a bit-wise split on this instance.

  • p2v

    Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

  • ps2v

    Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

  • set

    Sets the signal on a port.

  • get_result

    Returns the result of this gate's operation for given Signal s.

  • signal_in

    The input signal of the gate.

  • signal_out

    The output signal of the gate.

Attributes:

name instance-attribute

name: str

The name of the element.

!!! Do not modify this variable after instantiating it. Use NetlistElement.set_name() instead. Modifying this variable might lead to inconsistencies later on.

metadata class-attribute instance-attribute

Metadata of a netlist element.

Can be user-defined, or e. g. by Yosys (such as src for the HDL source). Is also grouped by categories, i.e. all metadata from Yosys can be accessed via Module.metadata["yosys"], or via Module.metadata.yosys, which both return a dictionary of all metadata. Read the documentation of MetaDataMixin for more information.

path property

Returns the InstancePath of the netlist element.

The InstancePath object is constructed using the element's type and its raw hierarchical path.

Returns:

  • InstancePath ( InstancePath ) –

    The hierarchical path of the netlist element.

type property

type: EType

The type of the element, which is an instance.

hierarchy_level property

hierarchy_level: int

The level of hierarchy of the element in the design.

The hierarchy level is the number of separators in the element's raw path. For example, a top-level instance has a hierarchy level of 0, while a direct submodule instance has a hierarchy level of 1.

Returns:

  • int ( int ) –

    The hierarchy level of the element.

has_parent property

has_parent: bool

Whether this object has a parent.

circuit property

circuit: 'Circuit'

The circuit object to which this netlist element belongs to.

  • For a module, returns the circuit to which the module belongs.
  • For any other netlist element, recursively returns the circuit of the parent, which ultimately leads to a module, to which the netlist element belongs.

Raises:

  • ParentNotFoundError

    If a parent cannot be resolved somewhere in the hierarchical chain.

  • ObjectNotFoundError

    If for a module no circuit is set.

has_circuit property

has_circuit: bool

Whether this netlist element has a defined circuit it belongs to.

Tries to access self.circuit and returns whether the call was successful. Can be used instead of a try-except clause around the call to NetlistElement.circuit.

locked property

locked: bool

True if this NetlistElement instance is locked (i.e. it is currently structurally unchangeable), False if it is mutable.

Can be changed via NetlistElement.change_mutability(bool).

Immutability is used to prevent accidental changes to the design.

is_placeholder_instance property

is_placeholder_instance: bool

A placeholder represents an element that does not have a specific path.

True if this NetlistElement instance represents a placeholder, False otherwise.

can_carry_signal property

can_carry_signal: bool

Whether this exact object is able to receive, pass or hold signal values.

True for ports (as they drive or receive values) and wires (as they pass the signals from driver to load ports) as well as their respective segments. False for instances and modules.

connections property

connections: Dict[str, Dict[int, WireSegmentPath]]

A dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port. Elements with no connection (i.e. the path is None) are excluded. In case these are needed, use Instance.get_connections() instead.

Example

{ 'port1': {1: WireSegmentPath('path/to/element1'), 2: WireSegmentPath('path/to/element2')}, 'port2': {1: WireSegmentPath('path/to/element3')} }

connection_str_paths property

connection_str_paths: Dict[str, Dict[int, str]]

Returns a dictionary mapping port names to their corresponding connection paths as strings.

The keys are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are the raw string paths.

Example

{ 'port1': {0: 'path.to.element1', 1: 'path.to.element2'}, 'port2': {0: 'path.to.element3'} }

ports property

A dictionary mapping port names to their corresponding Port objects.

The keys of the dictionary are the names of the ports. The values are Port objects representing the ports.

Returns:

input_ports property

input_ports: Tuple[Port[Instance], ...]

Returns a tuple of input ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as inputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the input ports.

output_ports property

output_ports: Tuple[Port[Instance], ...]

Returns a tuple of output ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as outputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the output ports.

has_unconnected_port_segments property

has_unconnected_port_segments: bool

Returns True if the instance has at least one unconnected port segment.

signals property

signals: Dict[str, SignalArray]

A dictionary with all signals currently present on all ports of this instance.

is_blackbox property

is_blackbox: bool

Flag indicating whether the instance represents neither a primitive element nor a module instance.

If True, this instance does not have a module definition, and is also not a basic component (i.e. a primitive gate instance) from the internal gate library, such as a gate or flip-flop.

y_width property

y_width: PositiveInt

Width of the gate, based on a certain port's width, depending on the actual gate.

a_width property

a_width: PositiveInt

Width of the gate's A port.

b_width property

b_width: PositiveInt

Width of the gate's B port.

is_combinational property

is_combinational: bool

Whether instances of this gate are considered combinational gates.

True for combinational gates, such as AND gates or arithmetic gates. False for flip-flops and latches.

is_sequential property

is_sequential: bool

Whether instances of this gate are considered sequential gates.

False for combinational gates, such as AND gates or arithmetic gates. True for flip-flops and latches.

output_port property

output_port: Port[Instance]

The output port of the gate.

data_width property

data_width: int

The data width of this instance.

Defaults to the data width of the output port. Can be overwritten in extended classes.

In contrast to self.width, which is used for the creation and initialization, this property is linked to the data width of the output port. This property is useful when the data width of the output port can be changed.

input_port property

input_port: Port[Instance]

The input port of the gate.

a_signed property

a_signed: bool

The signedness of input port A.

truth_table property

truth_table: Dict[Signal, Signal]

A simple truth table as a dictionary.

This dictionary contains the input-output mapping for unary gates that evaluate bitwise (e.g. Buffer, NotGate). Not implemented for arithmetic gates (e.g. NegGate, PosGate).

change_mutability

change_mutability(is_now_locked: bool, recursive: bool = False) -> Self

Change the mutability status of this instance and optionally its ports.

This method allows setting whether this instance can be modified or not. If recursive is set to True, it also applies the same mutability status to all ports of this instance.

Parameters:

  • is_now_locked

    (bool) –

    The new mutability status for this instance.

  • recursive

    (bool, default: False ) –

    Whether to apply the change recursively to its ports. Defaults to False.

evaluate

evaluate() -> None

Evaluates the gate's output signal based on its input signals.

This method is called when the gate's input signals change, and it updates the gate's output signal accordingly.

all_connections

all_connections(
    include_unconnected: bool,
) -> Dict[str, Dict[int, WireSegmentPath]]

Returns a dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port.

Parameters:

  • include_unconnected

    (bool) –

    Whether to include unconnected ports in the result.

Returns:

model_post_init

model_post_init(__context: object) -> None

Initializes the gate's ports and connections.

This method is called after the gate's attributes have been initialized, and it sets up the gate's ports and connections.

connect

connect(
    port_name: str,
    ws_path: Optional[WireSegmentPath],
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add connections to the specified port of this instance.

This method can establish multiple connections if a range of indices is provided.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection(s) should be established.

  • ws_path

    (Optional[WireSegmentPath]) –

    The path of the wire segment that will be connected to this port. If None, the associated port (segment) remains unconnected.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

Raises:

  • ObjectLockedError

    If this instance is currently locked, and no connection can be made.

disconnect

disconnect(port_name: str, index: Optional[int] = None) -> None

Remove an existing connection from a specified port of this instance.

This method disconnects the wire segment at the given index within the specified port_name.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be removed.

  • index

    (Optional[int], default: None ) –

    The bit index within the port for this disconnection. Defaults to None, which completely disconnects the port.

Raises:

get_connection

get_connection(
    port_name: str, index: Optional[NonNegativeInt] = None
) -> Union[WireSegmentPath, Dict[int, WireSegmentPath], None]

Retrieve the connection path associated with a specified port and bit index.

If index is provided, this method returns the wire segment path connected to that specific bit within the port. Otherwise, it returns all connections for the given port as a dictionary mapping indices to WireSegmentPaths.

Parameters:

  • port_name

    (str) –

    The name of the port for which to retrieve the connection(s).

  • index

    (Optional[NonNegativeInt], default: None ) –

    The bit index within the port. Defaults to None.

Returns:

modify_connection

modify_connection(
    port_name: str, ws_path: WireSegmentPath, index: NonNegativeInt = 0
) -> None

Modify an existing connection within a specified port of this instance.

This method updates the wire segment path at the given index within the specified port_name. If the index does not exist yet, it is newly added, changing the width of the port.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be modified.

  • ws_path

    (WireSegmentPath) –

    The new wire segment path for this connection.

  • index

    (NonNegativeInt, default: 0 ) –

    The bit index within the port. Defaults to 0.

connect_modify

connect_modify(
    port_name: str,
    ws_path: WireSegmentPath,
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add a new connection or modify an existing one within the specified port of this instance.

If the connection already exists at the given index and port_name, it will be modified. Otherwise, a new connection is added.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be established or updated.

  • ws_path

    (WireSegmentPath) –

    The path of the wire segment that will be connected to this port.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

tie_port

tie_port(name: str, index: NonNegativeInt, sig_value: LogicLevel) -> None

Set a constant signal value for the specified port and bit index.

If the specified port does not exist, an error message is logged and the function returns False. Otherwise, the method tries to set the constant signal value for that port and returns True if successful.

Does not work for instance output ports, as they are always driven by their parent instances.

Parameters:

  • name

    (str) –

    The name of the port.

  • index

    (NonNegativeInt) –

    The bit index within the port.

  • sig_value

    (LogicLevel) –

    The constant signal value to be set ('0', '1', or 'Z').

Raises:

  • ObjectNotFoundError

    If no such port or port segment exists.

  • AlreadyConnectedError

    (raised by: PortSegment.tie_signal) If this segment is belongs to a load port and is already connected to a wire, from which it receives its value.

  • InvalidDirectionError

    (raised by: PortSegment.tie_signal) If this port segment belongs to an instance output port, which is driven by the instance inputs and the instance's internal logic.

  • InvalidSignalError

    (raised by: PortSegment.tie_signal) If an invalid value is provided.

has_tied_ports

has_tied_ports() -> bool

Checks the ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any ports of this instance are tied to constant values. False otherwise, i.e. all ports are connected to wires.

has_tied_inputs

has_tied_inputs() -> bool

Checks the input ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any input ports of this instance are tied to constant values. False otherwise, i.e. all input ports are connected to wires.

has_tied_outputs

has_tied_outputs() -> bool

Checks the output ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any output ports of this instance are tied to constant values. False otherwise, i.e. all output ports are connected to wires.

update_signedness

update_signedness(port_name: str) -> None

Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

Parameters:

  • port_name

    (str) –

    The name of the port, of which the signedness value is retrieved.

split

split() -> Dict[NonNegativeInt, Self]

Performs a bit-wise split on this instance.

If this instance supports splitting and has a data width of n bit, this method splits this instance into n 1-bit instances. This works for instances, where each output bit depends only on the corresponding input bit(s), e.g. an AND gate or a D-Flipflop.

Returns:

  • Dict[NonNegativeInt, Self]

    Dict[int, Instance]: An n-bit large dictionary, where each key conforms to a bit of the original instance, and each value is an 1-bit instance representing the corresponding "slice" of the original instance.

Raises:

  • SplittingUnsupportedError

    If this instance does not support splitting. Happens for any gate or instance whose behavior depends on the whole bus, and splitting would make it lose its meaning.

p2v

p2v(
    port: ANY_PORT,
    exclude_indices: Optional[List[int]] = None,
    include_indices: Optional[List[int]] = None,
) -> str

Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a Port object and converts them to their corresponding Verilog signal structure (p2v -> Port to Verilog signal syntax). For each segment of the port, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port is set to a constant, the corresponding constant wire segment placeholder is used instead. Port segments can be excluded from the conversion by providing a list of indices to the exclude_indices parameter, indicating which segments should be excluded from the conversion (e.g. segments that are known to be unconnected). Vice versa, only a certain subset of the port's segments may be converted to Verilog syntax, if include_indices is a given list of port indices. All indices not present in the list will be excluded from the conversion.

Parameters:

  • port

    (Port) –

    The Port object to convert.

  • exclude_indices

    (List[int], default: None ) –

    A list of indices to exclude from the conversion. Defaults to None.

  • include_indices

    (List[int], default: None ) –

    A list of indices (i.e. port slices) to include only for the conversion. Defaults to None.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

  • ObjectNotFoundError

    If the wire connected to a certain port segment could not be found.

  • UnsupportedOperationError

    If both exclude_indices and include_indices are specified. Only one of both may be given when calling this method.

ps2v

Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a PortSegment dictionary and converts them to their corresponding Verilog signal structure (ps2v -> PortSegment to Verilog signal syntax). For each segment, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port segment is set to a constant, the corresponding constant wire segment placeholder is used instead.

Parameters:

  • ps_dict

    (Dict[int, PortSegment]) –

    The PortSegment dictionary to convert. Each key (int) conforms to the index of the associated PortSegment object.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

set

set(
    port_name: str,
    new_signal: SignalOrLogicLevel,
    idx: Union[int, List[int]] = 0,
) -> None

Sets the signal on a port.

Parameters:

  • port_name

    (str) –

    The name of the port to set the signal on.

  • new_signal

    (Signal) –

    The new signal value.

  • idx

    (Union[int, List[int]], default: 0 ) –

    The index (or indices) to apply the given signal to. Can either be an integer (single index to set) or an iterable of integers (e.g. a list of indices). For every integer of the iterable the signal value of the corresponding port index is set to the given new_signal. Defaults to 0.

Example

from netlist_carpentry.utils.gate_factory import and_gate module = Module(name='m') a = module.create_port('a', 'input', width=6) instance = and_gate(module, 'inst', A=a)

This sets the value of bit 0 of port A to HIGH

instance.set('A', 1, 0) instance.ports['A'].signal_str 'xxxxx1'

This sets the value of bits 1, 3 and 5 of port A to LOW, leaving the other bits as they already are.

instance.set('A', 0, [1, 3, 5]) instance.ports['A'].signal_str '0x0x01'

get_result

get_result(s: Signal) -> Signal

Returns the result of this gate's operation for given Signal s.

This method is only implemented for bitwise evaluating gates (e.g. Buffer, NotGate). This method raises an UnsupportedOperationError if used on arithmetic gates (e.g. PosGate, NegGate).

For vector-level operations on full signal arrays, use :meth:get_result_vector instead.

Parameters:

  • s

    (Signal) –

    The Signal, i.e. the input operand.

Raises:

Returns:

  • Signal ( Signal ) –

    The result of this gate's operation on the given signals.

signal_in

signal_in(idx: NonNegativeInt = 0) -> Signal

The input signal of the gate.

Returns:

  • Signal ( Signal ) –

    The input signal of the gate.

signal_out

signal_out(idx: NonNegativeInt = 0) -> Signal

The output signal of the gate.

Returns:

  • Signal ( Signal ) –

    The output signal of the gate.

NegGate

Bases: UnaryGate, BaseModel

An arithmetic negator gate.

An arithmetic negator gate is a gate that returns the two's complement of its input signal.

Methods:

  • change_mutability

    Change the mutability status of this instance and optionally its ports.

  • evaluate

    Evaluates the gate's output signal based on its input signals.

  • all_connections

    Returns a dictionary mapping port names to their corresponding connection paths.

  • model_post_init

    Initializes the gate's ports and connections.

  • connect

    Add connections to the specified port of this instance.

  • disconnect

    Remove an existing connection from a specified port of this instance.

  • get_connection

    Retrieve the connection path associated with a specified port and bit index.

  • modify_connection

    Modify an existing connection within a specified port of this instance.

  • connect_modify

    Add a new connection or modify an existing one within the specified port of this instance.

  • tie_port

    Set a constant signal value for the specified port and bit index.

  • has_tied_ports

    Checks the ports of this instance whether any are tied to constant values.

  • has_tied_inputs

    Checks the input ports of this instance whether any are tied to constant values.

  • has_tied_outputs

    Checks the output ports of this instance whether any are tied to constant values.

  • update_signedness

    Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

  • split

    Performs a bit-wise split on this instance.

  • p2v

    Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

  • ps2v

    Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

  • set

    Sets the signal on a port.

  • get_result

    Returns the result of this gate's operation for given Signal s.

  • signal_in

    The input signal of the gate.

  • signal_out

    The output signal of the gate.

Attributes:

name instance-attribute

name: str

The name of the element.

!!! Do not modify this variable after instantiating it. Use NetlistElement.set_name() instead. Modifying this variable might lead to inconsistencies later on.

metadata class-attribute instance-attribute

Metadata of a netlist element.

Can be user-defined, or e. g. by Yosys (such as src for the HDL source). Is also grouped by categories, i.e. all metadata from Yosys can be accessed via Module.metadata["yosys"], or via Module.metadata.yosys, which both return a dictionary of all metadata. Read the documentation of MetaDataMixin for more information.

path property

Returns the InstancePath of the netlist element.

The InstancePath object is constructed using the element's type and its raw hierarchical path.

Returns:

  • InstancePath ( InstancePath ) –

    The hierarchical path of the netlist element.

type property

type: EType

The type of the element, which is an instance.

hierarchy_level property

hierarchy_level: int

The level of hierarchy of the element in the design.

The hierarchy level is the number of separators in the element's raw path. For example, a top-level instance has a hierarchy level of 0, while a direct submodule instance has a hierarchy level of 1.

Returns:

  • int ( int ) –

    The hierarchy level of the element.

has_parent property

has_parent: bool

Whether this object has a parent.

circuit property

circuit: 'Circuit'

The circuit object to which this netlist element belongs to.

  • For a module, returns the circuit to which the module belongs.
  • For any other netlist element, recursively returns the circuit of the parent, which ultimately leads to a module, to which the netlist element belongs.

Raises:

  • ParentNotFoundError

    If a parent cannot be resolved somewhere in the hierarchical chain.

  • ObjectNotFoundError

    If for a module no circuit is set.

has_circuit property

has_circuit: bool

Whether this netlist element has a defined circuit it belongs to.

Tries to access self.circuit and returns whether the call was successful. Can be used instead of a try-except clause around the call to NetlistElement.circuit.

locked property

locked: bool

True if this NetlistElement instance is locked (i.e. it is currently structurally unchangeable), False if it is mutable.

Can be changed via NetlistElement.change_mutability(bool).

Immutability is used to prevent accidental changes to the design.

is_placeholder_instance property

is_placeholder_instance: bool

A placeholder represents an element that does not have a specific path.

True if this NetlistElement instance represents a placeholder, False otherwise.

can_carry_signal property

can_carry_signal: bool

Whether this exact object is able to receive, pass or hold signal values.

True for ports (as they drive or receive values) and wires (as they pass the signals from driver to load ports) as well as their respective segments. False for instances and modules.

connections property

connections: Dict[str, Dict[int, WireSegmentPath]]

A dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port. Elements with no connection (i.e. the path is None) are excluded. In case these are needed, use Instance.get_connections() instead.

Example

{ 'port1': {1: WireSegmentPath('path/to/element1'), 2: WireSegmentPath('path/to/element2')}, 'port2': {1: WireSegmentPath('path/to/element3')} }

connection_str_paths property

connection_str_paths: Dict[str, Dict[int, str]]

Returns a dictionary mapping port names to their corresponding connection paths as strings.

The keys are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are the raw string paths.

Example

{ 'port1': {0: 'path.to.element1', 1: 'path.to.element2'}, 'port2': {0: 'path.to.element3'} }

ports property

A dictionary mapping port names to their corresponding Port objects.

The keys of the dictionary are the names of the ports. The values are Port objects representing the ports.

Returns:

input_ports property

input_ports: Tuple[Port[Instance], ...]

Returns a tuple of input ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as inputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the input ports.

output_ports property

output_ports: Tuple[Port[Instance], ...]

Returns a tuple of output ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as outputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the output ports.

has_unconnected_port_segments property

has_unconnected_port_segments: bool

Returns True if the instance has at least one unconnected port segment.

signals property

signals: Dict[str, SignalArray]

A dictionary with all signals currently present on all ports of this instance.

is_blackbox property

is_blackbox: bool

Flag indicating whether the instance represents neither a primitive element nor a module instance.

If True, this instance does not have a module definition, and is also not a basic component (i.e. a primitive gate instance) from the internal gate library, such as a gate or flip-flop.

y_width property

y_width: PositiveInt

Width of the gate, based on a certain port's width, depending on the actual gate.

a_width property

a_width: PositiveInt

Width of the gate's A port.

b_width property

b_width: PositiveInt

Width of the gate's B port.

is_combinational property

is_combinational: bool

Whether instances of this gate are considered combinational gates.

True for combinational gates, such as AND gates or arithmetic gates. False for flip-flops and latches.

is_sequential property

is_sequential: bool

Whether instances of this gate are considered sequential gates.

False for combinational gates, such as AND gates or arithmetic gates. True for flip-flops and latches.

output_port property

output_port: Port[Instance]

The output port of the gate.

data_width property

data_width: int

The data width of this instance.

Defaults to the data width of the output port. Can be overwritten in extended classes.

In contrast to self.width, which is used for the creation and initialization, this property is linked to the data width of the output port. This property is useful when the data width of the output port can be changed.

input_port property

input_port: Port[Instance]

The input port of the gate.

a_signed property

a_signed: bool

The signedness of input port A.

truth_table property

truth_table: Dict[Signal, Signal]

A simple truth table as a dictionary.

This dictionary contains the input-output mapping for unary gates that evaluate bitwise (e.g. Buffer, NotGate). Not implemented for arithmetic gates (e.g. NegGate, PosGate).

change_mutability

change_mutability(is_now_locked: bool, recursive: bool = False) -> Self

Change the mutability status of this instance and optionally its ports.

This method allows setting whether this instance can be modified or not. If recursive is set to True, it also applies the same mutability status to all ports of this instance.

Parameters:

  • is_now_locked

    (bool) –

    The new mutability status for this instance.

  • recursive

    (bool, default: False ) –

    Whether to apply the change recursively to its ports. Defaults to False.

evaluate

evaluate() -> None

Evaluates the gate's output signal based on its input signals.

This method is called when the gate's input signals change, and it updates the gate's output signal accordingly.

all_connections

all_connections(
    include_unconnected: bool,
) -> Dict[str, Dict[int, WireSegmentPath]]

Returns a dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port.

Parameters:

  • include_unconnected

    (bool) –

    Whether to include unconnected ports in the result.

Returns:

model_post_init

model_post_init(__context: object) -> None

Initializes the gate's ports and connections.

This method is called after the gate's attributes have been initialized, and it sets up the gate's ports and connections.

connect

connect(
    port_name: str,
    ws_path: Optional[WireSegmentPath],
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add connections to the specified port of this instance.

This method can establish multiple connections if a range of indices is provided.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection(s) should be established.

  • ws_path

    (Optional[WireSegmentPath]) –

    The path of the wire segment that will be connected to this port. If None, the associated port (segment) remains unconnected.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

Raises:

  • ObjectLockedError

    If this instance is currently locked, and no connection can be made.

disconnect

disconnect(port_name: str, index: Optional[int] = None) -> None

Remove an existing connection from a specified port of this instance.

This method disconnects the wire segment at the given index within the specified port_name.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be removed.

  • index

    (Optional[int], default: None ) –

    The bit index within the port for this disconnection. Defaults to None, which completely disconnects the port.

Raises:

get_connection

get_connection(
    port_name: str, index: Optional[NonNegativeInt] = None
) -> Union[WireSegmentPath, Dict[int, WireSegmentPath], None]

Retrieve the connection path associated with a specified port and bit index.

If index is provided, this method returns the wire segment path connected to that specific bit within the port. Otherwise, it returns all connections for the given port as a dictionary mapping indices to WireSegmentPaths.

Parameters:

  • port_name

    (str) –

    The name of the port for which to retrieve the connection(s).

  • index

    (Optional[NonNegativeInt], default: None ) –

    The bit index within the port. Defaults to None.

Returns:

modify_connection

modify_connection(
    port_name: str, ws_path: WireSegmentPath, index: NonNegativeInt = 0
) -> None

Modify an existing connection within a specified port of this instance.

This method updates the wire segment path at the given index within the specified port_name. If the index does not exist yet, it is newly added, changing the width of the port.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be modified.

  • ws_path

    (WireSegmentPath) –

    The new wire segment path for this connection.

  • index

    (NonNegativeInt, default: 0 ) –

    The bit index within the port. Defaults to 0.

connect_modify

connect_modify(
    port_name: str,
    ws_path: WireSegmentPath,
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add a new connection or modify an existing one within the specified port of this instance.

If the connection already exists at the given index and port_name, it will be modified. Otherwise, a new connection is added.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be established or updated.

  • ws_path

    (WireSegmentPath) –

    The path of the wire segment that will be connected to this port.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

tie_port

tie_port(name: str, index: NonNegativeInt, sig_value: LogicLevel) -> None

Set a constant signal value for the specified port and bit index.

If the specified port does not exist, an error message is logged and the function returns False. Otherwise, the method tries to set the constant signal value for that port and returns True if successful.

Does not work for instance output ports, as they are always driven by their parent instances.

Parameters:

  • name

    (str) –

    The name of the port.

  • index

    (NonNegativeInt) –

    The bit index within the port.

  • sig_value

    (LogicLevel) –

    The constant signal value to be set ('0', '1', or 'Z').

Raises:

  • ObjectNotFoundError

    If no such port or port segment exists.

  • AlreadyConnectedError

    (raised by: PortSegment.tie_signal) If this segment is belongs to a load port and is already connected to a wire, from which it receives its value.

  • InvalidDirectionError

    (raised by: PortSegment.tie_signal) If this port segment belongs to an instance output port, which is driven by the instance inputs and the instance's internal logic.

  • InvalidSignalError

    (raised by: PortSegment.tie_signal) If an invalid value is provided.

has_tied_ports

has_tied_ports() -> bool

Checks the ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any ports of this instance are tied to constant values. False otherwise, i.e. all ports are connected to wires.

has_tied_inputs

has_tied_inputs() -> bool

Checks the input ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any input ports of this instance are tied to constant values. False otherwise, i.e. all input ports are connected to wires.

has_tied_outputs

has_tied_outputs() -> bool

Checks the output ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any output ports of this instance are tied to constant values. False otherwise, i.e. all output ports are connected to wires.

update_signedness

update_signedness(port_name: str) -> None

Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

Parameters:

  • port_name

    (str) –

    The name of the port, of which the signedness value is retrieved.

split

split() -> Dict[NonNegativeInt, Self]

Performs a bit-wise split on this instance.

If this instance supports splitting and has a data width of n bit, this method splits this instance into n 1-bit instances. This works for instances, where each output bit depends only on the corresponding input bit(s), e.g. an AND gate or a D-Flipflop.

Returns:

  • Dict[NonNegativeInt, Self]

    Dict[int, Instance]: An n-bit large dictionary, where each key conforms to a bit of the original instance, and each value is an 1-bit instance representing the corresponding "slice" of the original instance.

Raises:

  • SplittingUnsupportedError

    If this instance does not support splitting. Happens for any gate or instance whose behavior depends on the whole bus, and splitting would make it lose its meaning.

p2v

p2v(
    port: ANY_PORT,
    exclude_indices: Optional[List[int]] = None,
    include_indices: Optional[List[int]] = None,
) -> str

Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a Port object and converts them to their corresponding Verilog signal structure (p2v -> Port to Verilog signal syntax). For each segment of the port, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port is set to a constant, the corresponding constant wire segment placeholder is used instead. Port segments can be excluded from the conversion by providing a list of indices to the exclude_indices parameter, indicating which segments should be excluded from the conversion (e.g. segments that are known to be unconnected). Vice versa, only a certain subset of the port's segments may be converted to Verilog syntax, if include_indices is a given list of port indices. All indices not present in the list will be excluded from the conversion.

Parameters:

  • port

    (Port) –

    The Port object to convert.

  • exclude_indices

    (List[int], default: None ) –

    A list of indices to exclude from the conversion. Defaults to None.

  • include_indices

    (List[int], default: None ) –

    A list of indices (i.e. port slices) to include only for the conversion. Defaults to None.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

  • ObjectNotFoundError

    If the wire connected to a certain port segment could not be found.

  • UnsupportedOperationError

    If both exclude_indices and include_indices are specified. Only one of both may be given when calling this method.

ps2v

Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a PortSegment dictionary and converts them to their corresponding Verilog signal structure (ps2v -> PortSegment to Verilog signal syntax). For each segment, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port segment is set to a constant, the corresponding constant wire segment placeholder is used instead.

Parameters:

  • ps_dict

    (Dict[int, PortSegment]) –

    The PortSegment dictionary to convert. Each key (int) conforms to the index of the associated PortSegment object.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

set

set(
    port_name: str,
    new_signal: SignalOrLogicLevel,
    idx: Union[int, List[int]] = 0,
) -> None

Sets the signal on a port.

Parameters:

  • port_name

    (str) –

    The name of the port to set the signal on.

  • new_signal

    (Signal) –

    The new signal value.

  • idx

    (Union[int, List[int]], default: 0 ) –

    The index (or indices) to apply the given signal to. Can either be an integer (single index to set) or an iterable of integers (e.g. a list of indices). For every integer of the iterable the signal value of the corresponding port index is set to the given new_signal. Defaults to 0.

Example

from netlist_carpentry.utils.gate_factory import and_gate module = Module(name='m') a = module.create_port('a', 'input', width=6) instance = and_gate(module, 'inst', A=a)

This sets the value of bit 0 of port A to HIGH

instance.set('A', 1, 0) instance.ports['A'].signal_str 'xxxxx1'

This sets the value of bits 1, 3 and 5 of port A to LOW, leaving the other bits as they already are.

instance.set('A', 0, [1, 3, 5]) instance.ports['A'].signal_str '0x0x01'

get_result

get_result(s: Signal) -> Signal

Returns the result of this gate's operation for given Signal s.

This method is only implemented for bitwise evaluating gates (e.g. Buffer, NotGate). This method raises an UnsupportedOperationError if used on arithmetic gates (e.g. PosGate, NegGate).

For vector-level operations on full signal arrays, use :meth:get_result_vector instead.

Parameters:

  • s

    (Signal) –

    The Signal, i.e. the input operand.

Raises:

Returns:

  • Signal ( Signal ) –

    The result of this gate's operation on the given signals.

signal_in

signal_in(idx: NonNegativeInt = 0) -> Signal

The input signal of the gate.

Returns:

  • Signal ( Signal ) –

    The input signal of the gate.

signal_out

signal_out(idx: NonNegativeInt = 0) -> Signal

The output signal of the gate.

Returns:

  • Signal ( Signal ) –

    The output signal of the gate.

ReduceAnd

Bases: ReduceGate, BaseModel

A reduction AND gate.

A reduction AND gate performs a logical AND operation on all input signals. It produces a HIGH output signal if and only if all input signals are HIGH.

Methods:

  • change_mutability

    Change the mutability status of this instance and optionally its ports.

  • evaluate

    Evaluates the gate's output signal based on its input signals.

  • all_connections

    Returns a dictionary mapping port names to their corresponding connection paths.

  • model_post_init

    Initializes the gate's ports and connections.

  • connect

    Add connections to the specified port of this instance.

  • disconnect

    Remove an existing connection from a specified port of this instance.

  • get_connection

    Retrieve the connection path associated with a specified port and bit index.

  • modify_connection

    Modify an existing connection within a specified port of this instance.

  • connect_modify

    Add a new connection or modify an existing one within the specified port of this instance.

  • tie_port

    Set a constant signal value for the specified port and bit index.

  • has_tied_ports

    Checks the ports of this instance whether any are tied to constant values.

  • has_tied_inputs

    Checks the input ports of this instance whether any are tied to constant values.

  • has_tied_outputs

    Checks the output ports of this instance whether any are tied to constant values.

  • update_signedness

    Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

  • split

    Performs a bit-wise split on this instance.

  • p2v

    Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

  • ps2v

    Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

  • set

    Sets the signal on a port.

  • get_result

    Returns the result of this gate's operation for given Signal s.

  • get_result_vector

    Returns the result of this reduction gate's operation for a full signal vector.

  • signal_in

    The input signal of the gate.

  • signal_out

    The output signal of the gate.

Attributes:

reduce_operation property

reduce_operation: Callable[[Signal, Signal], Signal]

Provides a lambda function for this gate.

The lambda function takes two signals and executes this gate's operation on both of them. In junction with functools.reduce(), this reduces the input signal array down to a single bit by concatenating the operation of this gate bit-by-bit.

For a reduction AND gate, the output signal is HIGH if and only if all input signals are HIGH. If any input signal is LOW or undefined, the output signal will be LOW or undefined, respectively.

name instance-attribute

name: str

The name of the element.

!!! Do not modify this variable after instantiating it. Use NetlistElement.set_name() instead. Modifying this variable might lead to inconsistencies later on.

metadata class-attribute instance-attribute

Metadata of a netlist element.

Can be user-defined, or e. g. by Yosys (such as src for the HDL source). Is also grouped by categories, i.e. all metadata from Yosys can be accessed via Module.metadata["yosys"], or via Module.metadata.yosys, which both return a dictionary of all metadata. Read the documentation of MetaDataMixin for more information.

path property

Returns the InstancePath of the netlist element.

The InstancePath object is constructed using the element's type and its raw hierarchical path.

Returns:

  • InstancePath ( InstancePath ) –

    The hierarchical path of the netlist element.

type property

type: EType

The type of the element, which is an instance.

hierarchy_level property

hierarchy_level: int

The level of hierarchy of the element in the design.

The hierarchy level is the number of separators in the element's raw path. For example, a top-level instance has a hierarchy level of 0, while a direct submodule instance has a hierarchy level of 1.

Returns:

  • int ( int ) –

    The hierarchy level of the element.

has_parent property

has_parent: bool

Whether this object has a parent.

circuit property

circuit: 'Circuit'

The circuit object to which this netlist element belongs to.

  • For a module, returns the circuit to which the module belongs.
  • For any other netlist element, recursively returns the circuit of the parent, which ultimately leads to a module, to which the netlist element belongs.

Raises:

  • ParentNotFoundError

    If a parent cannot be resolved somewhere in the hierarchical chain.

  • ObjectNotFoundError

    If for a module no circuit is set.

has_circuit property

has_circuit: bool

Whether this netlist element has a defined circuit it belongs to.

Tries to access self.circuit and returns whether the call was successful. Can be used instead of a try-except clause around the call to NetlistElement.circuit.

locked property

locked: bool

True if this NetlistElement instance is locked (i.e. it is currently structurally unchangeable), False if it is mutable.

Can be changed via NetlistElement.change_mutability(bool).

Immutability is used to prevent accidental changes to the design.

is_placeholder_instance property

is_placeholder_instance: bool

A placeholder represents an element that does not have a specific path.

True if this NetlistElement instance represents a placeholder, False otherwise.

can_carry_signal property

can_carry_signal: bool

Whether this exact object is able to receive, pass or hold signal values.

True for ports (as they drive or receive values) and wires (as they pass the signals from driver to load ports) as well as their respective segments. False for instances and modules.

connections property

connections: Dict[str, Dict[int, WireSegmentPath]]

A dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port. Elements with no connection (i.e. the path is None) are excluded. In case these are needed, use Instance.get_connections() instead.

Example

{ 'port1': {1: WireSegmentPath('path/to/element1'), 2: WireSegmentPath('path/to/element2')}, 'port2': {1: WireSegmentPath('path/to/element3')} }

connection_str_paths property

connection_str_paths: Dict[str, Dict[int, str]]

Returns a dictionary mapping port names to their corresponding connection paths as strings.

The keys are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are the raw string paths.

Example

{ 'port1': {0: 'path.to.element1', 1: 'path.to.element2'}, 'port2': {0: 'path.to.element3'} }

ports property

A dictionary mapping port names to their corresponding Port objects.

The keys of the dictionary are the names of the ports. The values are Port objects representing the ports.

Returns:

input_ports property

input_ports: Tuple[Port[Instance], ...]

Returns a tuple of input ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as inputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the input ports.

output_ports property

output_ports: Tuple[Port[Instance], ...]

Returns a tuple of output ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as outputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the output ports.

has_unconnected_port_segments property

has_unconnected_port_segments: bool

Returns True if the instance has at least one unconnected port segment.

signals property

signals: Dict[str, SignalArray]

A dictionary with all signals currently present on all ports of this instance.

is_blackbox property

is_blackbox: bool

Flag indicating whether the instance represents neither a primitive element nor a module instance.

If True, this instance does not have a module definition, and is also not a basic component (i.e. a primitive gate instance) from the internal gate library, such as a gate or flip-flop.

y_width property

y_width: PositiveInt

Width of the gate, which is always 1 for gates that reduce N-bit inputs to 1 bit.

a_width property

a_width: PositiveInt

Width of the gate's A port.

b_width property

b_width: PositiveInt

Width of the gate's B port.

is_combinational property

is_combinational: bool

Whether instances of this gate are considered combinational gates.

True for combinational gates, such as AND gates or arithmetic gates. False for flip-flops and latches.

is_sequential property

is_sequential: bool

Whether instances of this gate are considered sequential gates.

False for combinational gates, such as AND gates or arithmetic gates. True for flip-flops and latches.

output_port property

output_port: Port[Instance]

The output port of the gate.

data_width property

data_width: int

The data width of this instance.

Defaults to the data width of the output port. Can be overwritten in extended classes.

In contrast to self.width, which is used for the creation and initialization, this property is linked to the data width of the output port. This property is useful when the data width of the output port can be changed.

input_port property

input_port: Port[Instance]

The input port of the gate.

a_signed property

a_signed: bool

The signedness of input port A.

truth_table property

truth_table: Dict[Signal, Signal]

A simple truth table as a dictionary.

This dictionary contains the input-output mapping for unary gates that evaluate bitwise (e.g. Buffer, NotGate). Not implemented for arithmetic gates (e.g. NegGate, PosGate).

change_mutability

change_mutability(is_now_locked: bool, recursive: bool = False) -> Self

Change the mutability status of this instance and optionally its ports.

This method allows setting whether this instance can be modified or not. If recursive is set to True, it also applies the same mutability status to all ports of this instance.

Parameters:

  • is_now_locked

    (bool) –

    The new mutability status for this instance.

  • recursive

    (bool, default: False ) –

    Whether to apply the change recursively to its ports. Defaults to False.

evaluate

evaluate() -> None

Evaluates the gate's output signal based on its input signals.

This method is called when the gate's input signals change, and it updates the gate's output signal accordingly.

all_connections

all_connections(
    include_unconnected: bool,
) -> Dict[str, Dict[int, WireSegmentPath]]

Returns a dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port.

Parameters:

  • include_unconnected

    (bool) –

    Whether to include unconnected ports in the result.

Returns:

model_post_init

model_post_init(__context: object) -> None

Initializes the gate's ports and connections.

This method is called after the gate's attributes have been initialized, and it sets up the gate's ports and connections.

connect

connect(
    port_name: str,
    ws_path: Optional[WireSegmentPath],
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add connections to the specified port of this instance.

This method can establish multiple connections if a range of indices is provided.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection(s) should be established.

  • ws_path

    (Optional[WireSegmentPath]) –

    The path of the wire segment that will be connected to this port. If None, the associated port (segment) remains unconnected.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

Raises:

  • ObjectLockedError

    If this instance is currently locked, and no connection can be made.

disconnect

disconnect(port_name: str, index: Optional[int] = None) -> None

Remove an existing connection from a specified port of this instance.

This method disconnects the wire segment at the given index within the specified port_name.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be removed.

  • index

    (Optional[int], default: None ) –

    The bit index within the port for this disconnection. Defaults to None, which completely disconnects the port.

Raises:

get_connection

get_connection(
    port_name: str, index: Optional[NonNegativeInt] = None
) -> Union[WireSegmentPath, Dict[int, WireSegmentPath], None]

Retrieve the connection path associated with a specified port and bit index.

If index is provided, this method returns the wire segment path connected to that specific bit within the port. Otherwise, it returns all connections for the given port as a dictionary mapping indices to WireSegmentPaths.

Parameters:

  • port_name

    (str) –

    The name of the port for which to retrieve the connection(s).

  • index

    (Optional[NonNegativeInt], default: None ) –

    The bit index within the port. Defaults to None.

Returns:

modify_connection

modify_connection(
    port_name: str, ws_path: WireSegmentPath, index: NonNegativeInt = 0
) -> None

Modify an existing connection within a specified port of this instance.

This method updates the wire segment path at the given index within the specified port_name. If the index does not exist yet, it is newly added, changing the width of the port.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be modified.

  • ws_path

    (WireSegmentPath) –

    The new wire segment path for this connection.

  • index

    (NonNegativeInt, default: 0 ) –

    The bit index within the port. Defaults to 0.

connect_modify

connect_modify(
    port_name: str,
    ws_path: WireSegmentPath,
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add a new connection or modify an existing one within the specified port of this instance.

If the connection already exists at the given index and port_name, it will be modified. Otherwise, a new connection is added.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be established or updated.

  • ws_path

    (WireSegmentPath) –

    The path of the wire segment that will be connected to this port.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

tie_port

tie_port(name: str, index: NonNegativeInt, sig_value: LogicLevel) -> None

Set a constant signal value for the specified port and bit index.

If the specified port does not exist, an error message is logged and the function returns False. Otherwise, the method tries to set the constant signal value for that port and returns True if successful.

Does not work for instance output ports, as they are always driven by their parent instances.

Parameters:

  • name

    (str) –

    The name of the port.

  • index

    (NonNegativeInt) –

    The bit index within the port.

  • sig_value

    (LogicLevel) –

    The constant signal value to be set ('0', '1', or 'Z').

Raises:

  • ObjectNotFoundError

    If no such port or port segment exists.

  • AlreadyConnectedError

    (raised by: PortSegment.tie_signal) If this segment is belongs to a load port and is already connected to a wire, from which it receives its value.

  • InvalidDirectionError

    (raised by: PortSegment.tie_signal) If this port segment belongs to an instance output port, which is driven by the instance inputs and the instance's internal logic.

  • InvalidSignalError

    (raised by: PortSegment.tie_signal) If an invalid value is provided.

has_tied_ports

has_tied_ports() -> bool

Checks the ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any ports of this instance are tied to constant values. False otherwise, i.e. all ports are connected to wires.

has_tied_inputs

has_tied_inputs() -> bool

Checks the input ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any input ports of this instance are tied to constant values. False otherwise, i.e. all input ports are connected to wires.

has_tied_outputs

has_tied_outputs() -> bool

Checks the output ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any output ports of this instance are tied to constant values. False otherwise, i.e. all output ports are connected to wires.

update_signedness

update_signedness(port_name: str) -> None

Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

Parameters:

  • port_name

    (str) –

    The name of the port, of which the signedness value is retrieved.

split

split() -> Dict[NonNegativeInt, Self]

Performs a bit-wise split on this instance.

If this instance supports splitting and has a data width of n bit, this method splits this instance into n 1-bit instances. This works for instances, where each output bit depends only on the corresponding input bit(s), e.g. an AND gate or a D-Flipflop.

Returns:

  • Dict[NonNegativeInt, Self]

    Dict[int, Instance]: An n-bit large dictionary, where each key conforms to a bit of the original instance, and each value is an 1-bit instance representing the corresponding "slice" of the original instance.

Raises:

  • SplittingUnsupportedError

    If this instance does not support splitting. Happens for any gate or instance whose behavior depends on the whole bus, and splitting would make it lose its meaning.

p2v

p2v(
    port: ANY_PORT,
    exclude_indices: Optional[List[int]] = None,
    include_indices: Optional[List[int]] = None,
) -> str

Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a Port object and converts them to their corresponding Verilog signal structure (p2v -> Port to Verilog signal syntax). For each segment of the port, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port is set to a constant, the corresponding constant wire segment placeholder is used instead. Port segments can be excluded from the conversion by providing a list of indices to the exclude_indices parameter, indicating which segments should be excluded from the conversion (e.g. segments that are known to be unconnected). Vice versa, only a certain subset of the port's segments may be converted to Verilog syntax, if include_indices is a given list of port indices. All indices not present in the list will be excluded from the conversion.

Parameters:

  • port

    (Port) –

    The Port object to convert.

  • exclude_indices

    (List[int], default: None ) –

    A list of indices to exclude from the conversion. Defaults to None.

  • include_indices

    (List[int], default: None ) –

    A list of indices (i.e. port slices) to include only for the conversion. Defaults to None.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

  • ObjectNotFoundError

    If the wire connected to a certain port segment could not be found.

  • UnsupportedOperationError

    If both exclude_indices and include_indices are specified. Only one of both may be given when calling this method.

ps2v

Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a PortSegment dictionary and converts them to their corresponding Verilog signal structure (ps2v -> PortSegment to Verilog signal syntax). For each segment, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port segment is set to a constant, the corresponding constant wire segment placeholder is used instead.

Parameters:

  • ps_dict

    (Dict[int, PortSegment]) –

    The PortSegment dictionary to convert. Each key (int) conforms to the index of the associated PortSegment object.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

set

set(
    port_name: str,
    new_signal: SignalOrLogicLevel,
    idx: Union[int, List[int]] = 0,
) -> None

Sets the signal on a port.

Parameters:

  • port_name

    (str) –

    The name of the port to set the signal on.

  • new_signal

    (Signal) –

    The new signal value.

  • idx

    (Union[int, List[int]], default: 0 ) –

    The index (or indices) to apply the given signal to. Can either be an integer (single index to set) or an iterable of integers (e.g. a list of indices). For every integer of the iterable the signal value of the corresponding port index is set to the given new_signal. Defaults to 0.

Example

from netlist_carpentry.utils.gate_factory import and_gate module = Module(name='m') a = module.create_port('a', 'input', width=6) instance = and_gate(module, 'inst', A=a)

This sets the value of bit 0 of port A to HIGH

instance.set('A', 1, 0) instance.ports['A'].signal_str 'xxxxx1'

This sets the value of bits 1, 3 and 5 of port A to LOW, leaving the other bits as they already are.

instance.set('A', 0, [1, 3, 5]) instance.ports['A'].signal_str '0x0x01'

get_result

get_result(s: Signal) -> Signal

Returns the result of this gate's operation for given Signal s.

This method is only implemented for bitwise evaluating gates (e.g. Buffer, NotGate). This method raises an UnsupportedOperationError if used on arithmetic gates (e.g. PosGate, NegGate).

For vector-level operations on full signal arrays, use :meth:get_result_vector instead.

Parameters:

  • s

    (Signal) –

    The Signal, i.e. the input operand.

Raises:

Returns:

  • Signal ( Signal ) –

    The result of this gate's operation on the given signals.

get_result_vector

get_result_vector(s: SignalArray) -> SignalArray

Returns the result of this reduction gate's operation for a full signal vector.

Reduces an N-bit :class:SignalArray to a 1-bit :class:SignalArray by applying :meth:reduce_operation across all bits using :func:functools.reduce.

Parameters:

Returns:

  • SignalArray ( SignalArray ) –

    A 1-bit SignalArray containing the reduction result.

signal_in

signal_in(idx: NonNegativeInt = 0) -> Signal

The input signal of the gate.

Returns:

  • Signal ( Signal ) –

    The input signal of the gate.

signal_out

signal_out() -> Signal

The output signal of the gate.

ReduceOr

Bases: ReduceGate, BaseModel

A reduction OR gate.

A reduction OR gate performs a logical OR operation on all input signals. It produces a HIGH output signal if at least one input signal is HIGH.

Methods:

  • change_mutability

    Change the mutability status of this instance and optionally its ports.

  • evaluate

    Evaluates the gate's output signal based on its input signals.

  • all_connections

    Returns a dictionary mapping port names to their corresponding connection paths.

  • model_post_init

    Initializes the gate's ports and connections.

  • connect

    Add connections to the specified port of this instance.

  • disconnect

    Remove an existing connection from a specified port of this instance.

  • get_connection

    Retrieve the connection path associated with a specified port and bit index.

  • modify_connection

    Modify an existing connection within a specified port of this instance.

  • connect_modify

    Add a new connection or modify an existing one within the specified port of this instance.

  • tie_port

    Set a constant signal value for the specified port and bit index.

  • has_tied_ports

    Checks the ports of this instance whether any are tied to constant values.

  • has_tied_inputs

    Checks the input ports of this instance whether any are tied to constant values.

  • has_tied_outputs

    Checks the output ports of this instance whether any are tied to constant values.

  • update_signedness

    Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

  • split

    Performs a bit-wise split on this instance.

  • p2v

    Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

  • ps2v

    Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

  • set

    Sets the signal on a port.

  • get_result

    Returns the result of this gate's operation for given Signal s.

  • get_result_vector

    Returns the result of this reduction gate's operation for a full signal vector.

  • signal_in

    The input signal of the gate.

  • signal_out

    The output signal of the gate.

Attributes:

reduce_operation property

reduce_operation: Callable[[Signal, Signal], Signal]

Provides a lambda function for this gate.

The lambda function takes two signals and executes this gate's operation on both of them. In junction with functools.reduce(), this reduces the input signal array down to a single bit by concatenating the operation of this gate bit-by-bit.

For a reduction OR gate, the output signal is HIGH if at least one input signal is HIGH. If all input signals are LOW or undefined, the output signal will be LOW or undefined, respectively.

name instance-attribute

name: str

The name of the element.

!!! Do not modify this variable after instantiating it. Use NetlistElement.set_name() instead. Modifying this variable might lead to inconsistencies later on.

metadata class-attribute instance-attribute

Metadata of a netlist element.

Can be user-defined, or e. g. by Yosys (such as src for the HDL source). Is also grouped by categories, i.e. all metadata from Yosys can be accessed via Module.metadata["yosys"], or via Module.metadata.yosys, which both return a dictionary of all metadata. Read the documentation of MetaDataMixin for more information.

path property

Returns the InstancePath of the netlist element.

The InstancePath object is constructed using the element's type and its raw hierarchical path.

Returns:

  • InstancePath ( InstancePath ) –

    The hierarchical path of the netlist element.

type property

type: EType

The type of the element, which is an instance.

hierarchy_level property

hierarchy_level: int

The level of hierarchy of the element in the design.

The hierarchy level is the number of separators in the element's raw path. For example, a top-level instance has a hierarchy level of 0, while a direct submodule instance has a hierarchy level of 1.

Returns:

  • int ( int ) –

    The hierarchy level of the element.

has_parent property

has_parent: bool

Whether this object has a parent.

circuit property

circuit: 'Circuit'

The circuit object to which this netlist element belongs to.

  • For a module, returns the circuit to which the module belongs.
  • For any other netlist element, recursively returns the circuit of the parent, which ultimately leads to a module, to which the netlist element belongs.

Raises:

  • ParentNotFoundError

    If a parent cannot be resolved somewhere in the hierarchical chain.

  • ObjectNotFoundError

    If for a module no circuit is set.

has_circuit property

has_circuit: bool

Whether this netlist element has a defined circuit it belongs to.

Tries to access self.circuit and returns whether the call was successful. Can be used instead of a try-except clause around the call to NetlistElement.circuit.

locked property

locked: bool

True if this NetlistElement instance is locked (i.e. it is currently structurally unchangeable), False if it is mutable.

Can be changed via NetlistElement.change_mutability(bool).

Immutability is used to prevent accidental changes to the design.

is_placeholder_instance property

is_placeholder_instance: bool

A placeholder represents an element that does not have a specific path.

True if this NetlistElement instance represents a placeholder, False otherwise.

can_carry_signal property

can_carry_signal: bool

Whether this exact object is able to receive, pass or hold signal values.

True for ports (as they drive or receive values) and wires (as they pass the signals from driver to load ports) as well as their respective segments. False for instances and modules.

connections property

connections: Dict[str, Dict[int, WireSegmentPath]]

A dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port. Elements with no connection (i.e. the path is None) are excluded. In case these are needed, use Instance.get_connections() instead.

Example

{ 'port1': {1: WireSegmentPath('path/to/element1'), 2: WireSegmentPath('path/to/element2')}, 'port2': {1: WireSegmentPath('path/to/element3')} }

connection_str_paths property

connection_str_paths: Dict[str, Dict[int, str]]

Returns a dictionary mapping port names to their corresponding connection paths as strings.

The keys are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are the raw string paths.

Example

{ 'port1': {0: 'path.to.element1', 1: 'path.to.element2'}, 'port2': {0: 'path.to.element3'} }

ports property

A dictionary mapping port names to their corresponding Port objects.

The keys of the dictionary are the names of the ports. The values are Port objects representing the ports.

Returns:

input_ports property

input_ports: Tuple[Port[Instance], ...]

Returns a tuple of input ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as inputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the input ports.

output_ports property

output_ports: Tuple[Port[Instance], ...]

Returns a tuple of output ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as outputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the output ports.

has_unconnected_port_segments property

has_unconnected_port_segments: bool

Returns True if the instance has at least one unconnected port segment.

signals property

signals: Dict[str, SignalArray]

A dictionary with all signals currently present on all ports of this instance.

is_blackbox property

is_blackbox: bool

Flag indicating whether the instance represents neither a primitive element nor a module instance.

If True, this instance does not have a module definition, and is also not a basic component (i.e. a primitive gate instance) from the internal gate library, such as a gate or flip-flop.

y_width property

y_width: PositiveInt

Width of the gate, which is always 1 for gates that reduce N-bit inputs to 1 bit.

a_width property

a_width: PositiveInt

Width of the gate's A port.

b_width property

b_width: PositiveInt

Width of the gate's B port.

is_combinational property

is_combinational: bool

Whether instances of this gate are considered combinational gates.

True for combinational gates, such as AND gates or arithmetic gates. False for flip-flops and latches.

is_sequential property

is_sequential: bool

Whether instances of this gate are considered sequential gates.

False for combinational gates, such as AND gates or arithmetic gates. True for flip-flops and latches.

output_port property

output_port: Port[Instance]

The output port of the gate.

data_width property

data_width: int

The data width of this instance.

Defaults to the data width of the output port. Can be overwritten in extended classes.

In contrast to self.width, which is used for the creation and initialization, this property is linked to the data width of the output port. This property is useful when the data width of the output port can be changed.

input_port property

input_port: Port[Instance]

The input port of the gate.

a_signed property

a_signed: bool

The signedness of input port A.

truth_table property

truth_table: Dict[Signal, Signal]

A simple truth table as a dictionary.

This dictionary contains the input-output mapping for unary gates that evaluate bitwise (e.g. Buffer, NotGate). Not implemented for arithmetic gates (e.g. NegGate, PosGate).

change_mutability

change_mutability(is_now_locked: bool, recursive: bool = False) -> Self

Change the mutability status of this instance and optionally its ports.

This method allows setting whether this instance can be modified or not. If recursive is set to True, it also applies the same mutability status to all ports of this instance.

Parameters:

  • is_now_locked

    (bool) –

    The new mutability status for this instance.

  • recursive

    (bool, default: False ) –

    Whether to apply the change recursively to its ports. Defaults to False.

evaluate

evaluate() -> None

Evaluates the gate's output signal based on its input signals.

This method is called when the gate's input signals change, and it updates the gate's output signal accordingly.

all_connections

all_connections(
    include_unconnected: bool,
) -> Dict[str, Dict[int, WireSegmentPath]]

Returns a dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port.

Parameters:

  • include_unconnected

    (bool) –

    Whether to include unconnected ports in the result.

Returns:

model_post_init

model_post_init(__context: object) -> None

Initializes the gate's ports and connections.

This method is called after the gate's attributes have been initialized, and it sets up the gate's ports and connections.

connect

connect(
    port_name: str,
    ws_path: Optional[WireSegmentPath],
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add connections to the specified port of this instance.

This method can establish multiple connections if a range of indices is provided.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection(s) should be established.

  • ws_path

    (Optional[WireSegmentPath]) –

    The path of the wire segment that will be connected to this port. If None, the associated port (segment) remains unconnected.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

Raises:

  • ObjectLockedError

    If this instance is currently locked, and no connection can be made.

disconnect

disconnect(port_name: str, index: Optional[int] = None) -> None

Remove an existing connection from a specified port of this instance.

This method disconnects the wire segment at the given index within the specified port_name.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be removed.

  • index

    (Optional[int], default: None ) –

    The bit index within the port for this disconnection. Defaults to None, which completely disconnects the port.

Raises:

get_connection

get_connection(
    port_name: str, index: Optional[NonNegativeInt] = None
) -> Union[WireSegmentPath, Dict[int, WireSegmentPath], None]

Retrieve the connection path associated with a specified port and bit index.

If index is provided, this method returns the wire segment path connected to that specific bit within the port. Otherwise, it returns all connections for the given port as a dictionary mapping indices to WireSegmentPaths.

Parameters:

  • port_name

    (str) –

    The name of the port for which to retrieve the connection(s).

  • index

    (Optional[NonNegativeInt], default: None ) –

    The bit index within the port. Defaults to None.

Returns:

modify_connection

modify_connection(
    port_name: str, ws_path: WireSegmentPath, index: NonNegativeInt = 0
) -> None

Modify an existing connection within a specified port of this instance.

This method updates the wire segment path at the given index within the specified port_name. If the index does not exist yet, it is newly added, changing the width of the port.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be modified.

  • ws_path

    (WireSegmentPath) –

    The new wire segment path for this connection.

  • index

    (NonNegativeInt, default: 0 ) –

    The bit index within the port. Defaults to 0.

connect_modify

connect_modify(
    port_name: str,
    ws_path: WireSegmentPath,
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add a new connection or modify an existing one within the specified port of this instance.

If the connection already exists at the given index and port_name, it will be modified. Otherwise, a new connection is added.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be established or updated.

  • ws_path

    (WireSegmentPath) –

    The path of the wire segment that will be connected to this port.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

tie_port

tie_port(name: str, index: NonNegativeInt, sig_value: LogicLevel) -> None

Set a constant signal value for the specified port and bit index.

If the specified port does not exist, an error message is logged and the function returns False. Otherwise, the method tries to set the constant signal value for that port and returns True if successful.

Does not work for instance output ports, as they are always driven by their parent instances.

Parameters:

  • name

    (str) –

    The name of the port.

  • index

    (NonNegativeInt) –

    The bit index within the port.

  • sig_value

    (LogicLevel) –

    The constant signal value to be set ('0', '1', or 'Z').

Raises:

  • ObjectNotFoundError

    If no such port or port segment exists.

  • AlreadyConnectedError

    (raised by: PortSegment.tie_signal) If this segment is belongs to a load port and is already connected to a wire, from which it receives its value.

  • InvalidDirectionError

    (raised by: PortSegment.tie_signal) If this port segment belongs to an instance output port, which is driven by the instance inputs and the instance's internal logic.

  • InvalidSignalError

    (raised by: PortSegment.tie_signal) If an invalid value is provided.

has_tied_ports

has_tied_ports() -> bool

Checks the ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any ports of this instance are tied to constant values. False otherwise, i.e. all ports are connected to wires.

has_tied_inputs

has_tied_inputs() -> bool

Checks the input ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any input ports of this instance are tied to constant values. False otherwise, i.e. all input ports are connected to wires.

has_tied_outputs

has_tied_outputs() -> bool

Checks the output ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any output ports of this instance are tied to constant values. False otherwise, i.e. all output ports are connected to wires.

update_signedness

update_signedness(port_name: str) -> None

Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

Parameters:

  • port_name

    (str) –

    The name of the port, of which the signedness value is retrieved.

split

split() -> Dict[NonNegativeInt, Self]

Performs a bit-wise split on this instance.

If this instance supports splitting and has a data width of n bit, this method splits this instance into n 1-bit instances. This works for instances, where each output bit depends only on the corresponding input bit(s), e.g. an AND gate or a D-Flipflop.

Returns:

  • Dict[NonNegativeInt, Self]

    Dict[int, Instance]: An n-bit large dictionary, where each key conforms to a bit of the original instance, and each value is an 1-bit instance representing the corresponding "slice" of the original instance.

Raises:

  • SplittingUnsupportedError

    If this instance does not support splitting. Happens for any gate or instance whose behavior depends on the whole bus, and splitting would make it lose its meaning.

p2v

p2v(
    port: ANY_PORT,
    exclude_indices: Optional[List[int]] = None,
    include_indices: Optional[List[int]] = None,
) -> str

Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a Port object and converts them to their corresponding Verilog signal structure (p2v -> Port to Verilog signal syntax). For each segment of the port, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port is set to a constant, the corresponding constant wire segment placeholder is used instead. Port segments can be excluded from the conversion by providing a list of indices to the exclude_indices parameter, indicating which segments should be excluded from the conversion (e.g. segments that are known to be unconnected). Vice versa, only a certain subset of the port's segments may be converted to Verilog syntax, if include_indices is a given list of port indices. All indices not present in the list will be excluded from the conversion.

Parameters:

  • port

    (Port) –

    The Port object to convert.

  • exclude_indices

    (List[int], default: None ) –

    A list of indices to exclude from the conversion. Defaults to None.

  • include_indices

    (List[int], default: None ) –

    A list of indices (i.e. port slices) to include only for the conversion. Defaults to None.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

  • ObjectNotFoundError

    If the wire connected to a certain port segment could not be found.

  • UnsupportedOperationError

    If both exclude_indices and include_indices are specified. Only one of both may be given when calling this method.

ps2v

Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a PortSegment dictionary and converts them to their corresponding Verilog signal structure (ps2v -> PortSegment to Verilog signal syntax). For each segment, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port segment is set to a constant, the corresponding constant wire segment placeholder is used instead.

Parameters:

  • ps_dict

    (Dict[int, PortSegment]) –

    The PortSegment dictionary to convert. Each key (int) conforms to the index of the associated PortSegment object.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

set

set(
    port_name: str,
    new_signal: SignalOrLogicLevel,
    idx: Union[int, List[int]] = 0,
) -> None

Sets the signal on a port.

Parameters:

  • port_name

    (str) –

    The name of the port to set the signal on.

  • new_signal

    (Signal) –

    The new signal value.

  • idx

    (Union[int, List[int]], default: 0 ) –

    The index (or indices) to apply the given signal to. Can either be an integer (single index to set) or an iterable of integers (e.g. a list of indices). For every integer of the iterable the signal value of the corresponding port index is set to the given new_signal. Defaults to 0.

Example

from netlist_carpentry.utils.gate_factory import and_gate module = Module(name='m') a = module.create_port('a', 'input', width=6) instance = and_gate(module, 'inst', A=a)

This sets the value of bit 0 of port A to HIGH

instance.set('A', 1, 0) instance.ports['A'].signal_str 'xxxxx1'

This sets the value of bits 1, 3 and 5 of port A to LOW, leaving the other bits as they already are.

instance.set('A', 0, [1, 3, 5]) instance.ports['A'].signal_str '0x0x01'

get_result

get_result(s: Signal) -> Signal

Returns the result of this gate's operation for given Signal s.

This method is only implemented for bitwise evaluating gates (e.g. Buffer, NotGate). This method raises an UnsupportedOperationError if used on arithmetic gates (e.g. PosGate, NegGate).

For vector-level operations on full signal arrays, use :meth:get_result_vector instead.

Parameters:

  • s

    (Signal) –

    The Signal, i.e. the input operand.

Raises:

Returns:

  • Signal ( Signal ) –

    The result of this gate's operation on the given signals.

get_result_vector

get_result_vector(s: SignalArray) -> SignalArray

Returns the result of this reduction gate's operation for a full signal vector.

Reduces an N-bit :class:SignalArray to a 1-bit :class:SignalArray by applying :meth:reduce_operation across all bits using :func:functools.reduce.

Parameters:

Returns:

  • SignalArray ( SignalArray ) –

    A 1-bit SignalArray containing the reduction result.

signal_in

signal_in(idx: NonNegativeInt = 0) -> Signal

The input signal of the gate.

Returns:

  • Signal ( Signal ) –

    The input signal of the gate.

signal_out

signal_out() -> Signal

The output signal of the gate.

ReduceBool

Bases: ReduceGate, BaseModel

A reduction Boolean gate.

A reduction Boolean gate performs a logical OR operation on all input signals, but with the effect of a double negation (i.e., '!(!wire_vector)' in Verilog). It produces a HIGH output signal if at least one input signal is HIGH.

Methods:

  • change_mutability

    Change the mutability status of this instance and optionally its ports.

  • evaluate

    Evaluates the gate's output signal based on its input signals.

  • all_connections

    Returns a dictionary mapping port names to their corresponding connection paths.

  • model_post_init

    Initializes the gate's ports and connections.

  • connect

    Add connections to the specified port of this instance.

  • disconnect

    Remove an existing connection from a specified port of this instance.

  • get_connection

    Retrieve the connection path associated with a specified port and bit index.

  • modify_connection

    Modify an existing connection within a specified port of this instance.

  • connect_modify

    Add a new connection or modify an existing one within the specified port of this instance.

  • tie_port

    Set a constant signal value for the specified port and bit index.

  • has_tied_ports

    Checks the ports of this instance whether any are tied to constant values.

  • has_tied_inputs

    Checks the input ports of this instance whether any are tied to constant values.

  • has_tied_outputs

    Checks the output ports of this instance whether any are tied to constant values.

  • update_signedness

    Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

  • split

    Performs a bit-wise split on this instance.

  • p2v

    Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

  • ps2v

    Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

  • set

    Sets the signal on a port.

  • get_result

    Returns the result of this gate's operation for given Signal s.

  • get_result_vector

    Returns the result of this reduction gate's operation for a full signal vector.

  • signal_in

    The input signal of the gate.

  • signal_out

    The output signal of the gate.

Attributes:

reduce_operation property

reduce_operation: Callable[[Signal, Signal], Signal]

Provides a lambda function for this gate.

The lambda function takes two signals and executes this gate's operation on both of them. In junction with functools.reduce(), this reduces the input signal array down to a single bit by concatenating the operation of this gate bit-by-bit.

For a reduction Boolean gate, the output signal is HIGH if at least one input signal is HIGH. If all input signals are LOW or undefined, the output signal will be LOW or undefined, respectively.

name instance-attribute

name: str

The name of the element.

!!! Do not modify this variable after instantiating it. Use NetlistElement.set_name() instead. Modifying this variable might lead to inconsistencies later on.

metadata class-attribute instance-attribute

Metadata of a netlist element.

Can be user-defined, or e. g. by Yosys (such as src for the HDL source). Is also grouped by categories, i.e. all metadata from Yosys can be accessed via Module.metadata["yosys"], or via Module.metadata.yosys, which both return a dictionary of all metadata. Read the documentation of MetaDataMixin for more information.

path property

Returns the InstancePath of the netlist element.

The InstancePath object is constructed using the element's type and its raw hierarchical path.

Returns:

  • InstancePath ( InstancePath ) –

    The hierarchical path of the netlist element.

type property

type: EType

The type of the element, which is an instance.

hierarchy_level property

hierarchy_level: int

The level of hierarchy of the element in the design.

The hierarchy level is the number of separators in the element's raw path. For example, a top-level instance has a hierarchy level of 0, while a direct submodule instance has a hierarchy level of 1.

Returns:

  • int ( int ) –

    The hierarchy level of the element.

has_parent property

has_parent: bool

Whether this object has a parent.

circuit property

circuit: 'Circuit'

The circuit object to which this netlist element belongs to.

  • For a module, returns the circuit to which the module belongs.
  • For any other netlist element, recursively returns the circuit of the parent, which ultimately leads to a module, to which the netlist element belongs.

Raises:

  • ParentNotFoundError

    If a parent cannot be resolved somewhere in the hierarchical chain.

  • ObjectNotFoundError

    If for a module no circuit is set.

has_circuit property

has_circuit: bool

Whether this netlist element has a defined circuit it belongs to.

Tries to access self.circuit and returns whether the call was successful. Can be used instead of a try-except clause around the call to NetlistElement.circuit.

locked property

locked: bool

True if this NetlistElement instance is locked (i.e. it is currently structurally unchangeable), False if it is mutable.

Can be changed via NetlistElement.change_mutability(bool).

Immutability is used to prevent accidental changes to the design.

is_placeholder_instance property

is_placeholder_instance: bool

A placeholder represents an element that does not have a specific path.

True if this NetlistElement instance represents a placeholder, False otherwise.

can_carry_signal property

can_carry_signal: bool

Whether this exact object is able to receive, pass or hold signal values.

True for ports (as they drive or receive values) and wires (as they pass the signals from driver to load ports) as well as their respective segments. False for instances and modules.

connections property

connections: Dict[str, Dict[int, WireSegmentPath]]

A dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port. Elements with no connection (i.e. the path is None) are excluded. In case these are needed, use Instance.get_connections() instead.

Example

{ 'port1': {1: WireSegmentPath('path/to/element1'), 2: WireSegmentPath('path/to/element2')}, 'port2': {1: WireSegmentPath('path/to/element3')} }

connection_str_paths property

connection_str_paths: Dict[str, Dict[int, str]]

Returns a dictionary mapping port names to their corresponding connection paths as strings.

The keys are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are the raw string paths.

Example

{ 'port1': {0: 'path.to.element1', 1: 'path.to.element2'}, 'port2': {0: 'path.to.element3'} }

ports property

A dictionary mapping port names to their corresponding Port objects.

The keys of the dictionary are the names of the ports. The values are Port objects representing the ports.

Returns:

input_ports property

input_ports: Tuple[Port[Instance], ...]

Returns a tuple of input ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as inputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the input ports.

output_ports property

output_ports: Tuple[Port[Instance], ...]

Returns a tuple of output ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as outputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the output ports.

has_unconnected_port_segments property

has_unconnected_port_segments: bool

Returns True if the instance has at least one unconnected port segment.

signals property

signals: Dict[str, SignalArray]

A dictionary with all signals currently present on all ports of this instance.

is_blackbox property

is_blackbox: bool

Flag indicating whether the instance represents neither a primitive element nor a module instance.

If True, this instance does not have a module definition, and is also not a basic component (i.e. a primitive gate instance) from the internal gate library, such as a gate or flip-flop.

y_width property

y_width: PositiveInt

Width of the gate, which is always 1 for gates that reduce N-bit inputs to 1 bit.

a_width property

a_width: PositiveInt

Width of the gate's A port.

b_width property

b_width: PositiveInt

Width of the gate's B port.

is_combinational property

is_combinational: bool

Whether instances of this gate are considered combinational gates.

True for combinational gates, such as AND gates or arithmetic gates. False for flip-flops and latches.

is_sequential property

is_sequential: bool

Whether instances of this gate are considered sequential gates.

False for combinational gates, such as AND gates or arithmetic gates. True for flip-flops and latches.

output_port property

output_port: Port[Instance]

The output port of the gate.

data_width property

data_width: int

The data width of this instance.

Defaults to the data width of the output port. Can be overwritten in extended classes.

In contrast to self.width, which is used for the creation and initialization, this property is linked to the data width of the output port. This property is useful when the data width of the output port can be changed.

input_port property

input_port: Port[Instance]

The input port of the gate.

a_signed property

a_signed: bool

The signedness of input port A.

truth_table property

truth_table: Dict[Signal, Signal]

A simple truth table as a dictionary.

This dictionary contains the input-output mapping for unary gates that evaluate bitwise (e.g. Buffer, NotGate). Not implemented for arithmetic gates (e.g. NegGate, PosGate).

change_mutability

change_mutability(is_now_locked: bool, recursive: bool = False) -> Self

Change the mutability status of this instance and optionally its ports.

This method allows setting whether this instance can be modified or not. If recursive is set to True, it also applies the same mutability status to all ports of this instance.

Parameters:

  • is_now_locked

    (bool) –

    The new mutability status for this instance.

  • recursive

    (bool, default: False ) –

    Whether to apply the change recursively to its ports. Defaults to False.

evaluate

evaluate() -> None

Evaluates the gate's output signal based on its input signals.

This method is called when the gate's input signals change, and it updates the gate's output signal accordingly.

all_connections

all_connections(
    include_unconnected: bool,
) -> Dict[str, Dict[int, WireSegmentPath]]

Returns a dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port.

Parameters:

  • include_unconnected

    (bool) –

    Whether to include unconnected ports in the result.

Returns:

model_post_init

model_post_init(__context: object) -> None

Initializes the gate's ports and connections.

This method is called after the gate's attributes have been initialized, and it sets up the gate's ports and connections.

connect

connect(
    port_name: str,
    ws_path: Optional[WireSegmentPath],
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add connections to the specified port of this instance.

This method can establish multiple connections if a range of indices is provided.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection(s) should be established.

  • ws_path

    (Optional[WireSegmentPath]) –

    The path of the wire segment that will be connected to this port. If None, the associated port (segment) remains unconnected.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

Raises:

  • ObjectLockedError

    If this instance is currently locked, and no connection can be made.

disconnect

disconnect(port_name: str, index: Optional[int] = None) -> None

Remove an existing connection from a specified port of this instance.

This method disconnects the wire segment at the given index within the specified port_name.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be removed.

  • index

    (Optional[int], default: None ) –

    The bit index within the port for this disconnection. Defaults to None, which completely disconnects the port.

Raises:

get_connection

get_connection(
    port_name: str, index: Optional[NonNegativeInt] = None
) -> Union[WireSegmentPath, Dict[int, WireSegmentPath], None]

Retrieve the connection path associated with a specified port and bit index.

If index is provided, this method returns the wire segment path connected to that specific bit within the port. Otherwise, it returns all connections for the given port as a dictionary mapping indices to WireSegmentPaths.

Parameters:

  • port_name

    (str) –

    The name of the port for which to retrieve the connection(s).

  • index

    (Optional[NonNegativeInt], default: None ) –

    The bit index within the port. Defaults to None.

Returns:

modify_connection

modify_connection(
    port_name: str, ws_path: WireSegmentPath, index: NonNegativeInt = 0
) -> None

Modify an existing connection within a specified port of this instance.

This method updates the wire segment path at the given index within the specified port_name. If the index does not exist yet, it is newly added, changing the width of the port.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be modified.

  • ws_path

    (WireSegmentPath) –

    The new wire segment path for this connection.

  • index

    (NonNegativeInt, default: 0 ) –

    The bit index within the port. Defaults to 0.

connect_modify

connect_modify(
    port_name: str,
    ws_path: WireSegmentPath,
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add a new connection or modify an existing one within the specified port of this instance.

If the connection already exists at the given index and port_name, it will be modified. Otherwise, a new connection is added.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be established or updated.

  • ws_path

    (WireSegmentPath) –

    The path of the wire segment that will be connected to this port.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

tie_port

tie_port(name: str, index: NonNegativeInt, sig_value: LogicLevel) -> None

Set a constant signal value for the specified port and bit index.

If the specified port does not exist, an error message is logged and the function returns False. Otherwise, the method tries to set the constant signal value for that port and returns True if successful.

Does not work for instance output ports, as they are always driven by their parent instances.

Parameters:

  • name

    (str) –

    The name of the port.

  • index

    (NonNegativeInt) –

    The bit index within the port.

  • sig_value

    (LogicLevel) –

    The constant signal value to be set ('0', '1', or 'Z').

Raises:

  • ObjectNotFoundError

    If no such port or port segment exists.

  • AlreadyConnectedError

    (raised by: PortSegment.tie_signal) If this segment is belongs to a load port and is already connected to a wire, from which it receives its value.

  • InvalidDirectionError

    (raised by: PortSegment.tie_signal) If this port segment belongs to an instance output port, which is driven by the instance inputs and the instance's internal logic.

  • InvalidSignalError

    (raised by: PortSegment.tie_signal) If an invalid value is provided.

has_tied_ports

has_tied_ports() -> bool

Checks the ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any ports of this instance are tied to constant values. False otherwise, i.e. all ports are connected to wires.

has_tied_inputs

has_tied_inputs() -> bool

Checks the input ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any input ports of this instance are tied to constant values. False otherwise, i.e. all input ports are connected to wires.

has_tied_outputs

has_tied_outputs() -> bool

Checks the output ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any output ports of this instance are tied to constant values. False otherwise, i.e. all output ports are connected to wires.

update_signedness

update_signedness(port_name: str) -> None

Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

Parameters:

  • port_name

    (str) –

    The name of the port, of which the signedness value is retrieved.

split

split() -> Dict[NonNegativeInt, Self]

Performs a bit-wise split on this instance.

If this instance supports splitting and has a data width of n bit, this method splits this instance into n 1-bit instances. This works for instances, where each output bit depends only on the corresponding input bit(s), e.g. an AND gate or a D-Flipflop.

Returns:

  • Dict[NonNegativeInt, Self]

    Dict[int, Instance]: An n-bit large dictionary, where each key conforms to a bit of the original instance, and each value is an 1-bit instance representing the corresponding "slice" of the original instance.

Raises:

  • SplittingUnsupportedError

    If this instance does not support splitting. Happens for any gate or instance whose behavior depends on the whole bus, and splitting would make it lose its meaning.

p2v

p2v(
    port: ANY_PORT,
    exclude_indices: Optional[List[int]] = None,
    include_indices: Optional[List[int]] = None,
) -> str

Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a Port object and converts them to their corresponding Verilog signal structure (p2v -> Port to Verilog signal syntax). For each segment of the port, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port is set to a constant, the corresponding constant wire segment placeholder is used instead. Port segments can be excluded from the conversion by providing a list of indices to the exclude_indices parameter, indicating which segments should be excluded from the conversion (e.g. segments that are known to be unconnected). Vice versa, only a certain subset of the port's segments may be converted to Verilog syntax, if include_indices is a given list of port indices. All indices not present in the list will be excluded from the conversion.

Parameters:

  • port

    (Port) –

    The Port object to convert.

  • exclude_indices

    (List[int], default: None ) –

    A list of indices to exclude from the conversion. Defaults to None.

  • include_indices

    (List[int], default: None ) –

    A list of indices (i.e. port slices) to include only for the conversion. Defaults to None.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

  • ObjectNotFoundError

    If the wire connected to a certain port segment could not be found.

  • UnsupportedOperationError

    If both exclude_indices and include_indices are specified. Only one of both may be given when calling this method.

ps2v

Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a PortSegment dictionary and converts them to their corresponding Verilog signal structure (ps2v -> PortSegment to Verilog signal syntax). For each segment, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port segment is set to a constant, the corresponding constant wire segment placeholder is used instead.

Parameters:

  • ps_dict

    (Dict[int, PortSegment]) –

    The PortSegment dictionary to convert. Each key (int) conforms to the index of the associated PortSegment object.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

set

set(
    port_name: str,
    new_signal: SignalOrLogicLevel,
    idx: Union[int, List[int]] = 0,
) -> None

Sets the signal on a port.

Parameters:

  • port_name

    (str) –

    The name of the port to set the signal on.

  • new_signal

    (Signal) –

    The new signal value.

  • idx

    (Union[int, List[int]], default: 0 ) –

    The index (or indices) to apply the given signal to. Can either be an integer (single index to set) or an iterable of integers (e.g. a list of indices). For every integer of the iterable the signal value of the corresponding port index is set to the given new_signal. Defaults to 0.

Example

from netlist_carpentry.utils.gate_factory import and_gate module = Module(name='m') a = module.create_port('a', 'input', width=6) instance = and_gate(module, 'inst', A=a)

This sets the value of bit 0 of port A to HIGH

instance.set('A', 1, 0) instance.ports['A'].signal_str 'xxxxx1'

This sets the value of bits 1, 3 and 5 of port A to LOW, leaving the other bits as they already are.

instance.set('A', 0, [1, 3, 5]) instance.ports['A'].signal_str '0x0x01'

get_result

get_result(s: Signal) -> Signal

Returns the result of this gate's operation for given Signal s.

This method is only implemented for bitwise evaluating gates (e.g. Buffer, NotGate). This method raises an UnsupportedOperationError if used on arithmetic gates (e.g. PosGate, NegGate).

For vector-level operations on full signal arrays, use :meth:get_result_vector instead.

Parameters:

  • s

    (Signal) –

    The Signal, i.e. the input operand.

Raises:

Returns:

  • Signal ( Signal ) –

    The result of this gate's operation on the given signals.

get_result_vector

get_result_vector(s: SignalArray) -> SignalArray

Returns the result of this reduction gate's operation for a full signal vector.

Reduces an N-bit :class:SignalArray to a 1-bit :class:SignalArray by applying :meth:reduce_operation across all bits using :func:functools.reduce.

Parameters:

Returns:

  • SignalArray ( SignalArray ) –

    A 1-bit SignalArray containing the reduction result.

signal_in

signal_in(idx: NonNegativeInt = 0) -> Signal

The input signal of the gate.

Returns:

  • Signal ( Signal ) –

    The input signal of the gate.

signal_out

signal_out() -> Signal

The output signal of the gate.

ReduceXor

Bases: ReduceGate, BaseModel

A reduction XOR gate.

A reduction XOR gate performs a logical XOR operation on all input signals. It produces a HIGH output signal if an odd number of input signals are HIGH.

Methods:

  • change_mutability

    Change the mutability status of this instance and optionally its ports.

  • evaluate

    Evaluates the gate's output signal based on its input signals.

  • all_connections

    Returns a dictionary mapping port names to their corresponding connection paths.

  • model_post_init

    Initializes the gate's ports and connections.

  • connect

    Add connections to the specified port of this instance.

  • disconnect

    Remove an existing connection from a specified port of this instance.

  • get_connection

    Retrieve the connection path associated with a specified port and bit index.

  • modify_connection

    Modify an existing connection within a specified port of this instance.

  • connect_modify

    Add a new connection or modify an existing one within the specified port of this instance.

  • tie_port

    Set a constant signal value for the specified port and bit index.

  • has_tied_ports

    Checks the ports of this instance whether any are tied to constant values.

  • has_tied_inputs

    Checks the input ports of this instance whether any are tied to constant values.

  • has_tied_outputs

    Checks the output ports of this instance whether any are tied to constant values.

  • update_signedness

    Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

  • split

    Performs a bit-wise split on this instance.

  • p2v

    Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

  • ps2v

    Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

  • set

    Sets the signal on a port.

  • get_result

    Returns the result of this gate's operation for given Signal s.

  • get_result_vector

    Returns the result of this reduction gate's operation for a full signal vector.

  • signal_in

    The input signal of the gate.

  • signal_out

    The output signal of the gate.

Attributes:

reduce_operation property

reduce_operation: Callable[[Signal, Signal], Signal]

Provides a lambda function for this gate.

The lambda function takes two signals and executes this gate's operation on both of them. In junction with functools.reduce(), this reduces the input signal array down to a single bit by concatenating the operation of this gate bit-by-bit.

For a reduction XOR gate, the output signal is HIGH if an odd number of input signals are HIGH. If an even number of input signals are HIGH or any input signal is undefined, the output signal will be LOW or undefined, respectively.

name instance-attribute

name: str

The name of the element.

!!! Do not modify this variable after instantiating it. Use NetlistElement.set_name() instead. Modifying this variable might lead to inconsistencies later on.

metadata class-attribute instance-attribute

Metadata of a netlist element.

Can be user-defined, or e. g. by Yosys (such as src for the HDL source). Is also grouped by categories, i.e. all metadata from Yosys can be accessed via Module.metadata["yosys"], or via Module.metadata.yosys, which both return a dictionary of all metadata. Read the documentation of MetaDataMixin for more information.

path property

Returns the InstancePath of the netlist element.

The InstancePath object is constructed using the element's type and its raw hierarchical path.

Returns:

  • InstancePath ( InstancePath ) –

    The hierarchical path of the netlist element.

type property

type: EType

The type of the element, which is an instance.

hierarchy_level property

hierarchy_level: int

The level of hierarchy of the element in the design.

The hierarchy level is the number of separators in the element's raw path. For example, a top-level instance has a hierarchy level of 0, while a direct submodule instance has a hierarchy level of 1.

Returns:

  • int ( int ) –

    The hierarchy level of the element.

has_parent property

has_parent: bool

Whether this object has a parent.

circuit property

circuit: 'Circuit'

The circuit object to which this netlist element belongs to.

  • For a module, returns the circuit to which the module belongs.
  • For any other netlist element, recursively returns the circuit of the parent, which ultimately leads to a module, to which the netlist element belongs.

Raises:

  • ParentNotFoundError

    If a parent cannot be resolved somewhere in the hierarchical chain.

  • ObjectNotFoundError

    If for a module no circuit is set.

has_circuit property

has_circuit: bool

Whether this netlist element has a defined circuit it belongs to.

Tries to access self.circuit and returns whether the call was successful. Can be used instead of a try-except clause around the call to NetlistElement.circuit.

locked property

locked: bool

True if this NetlistElement instance is locked (i.e. it is currently structurally unchangeable), False if it is mutable.

Can be changed via NetlistElement.change_mutability(bool).

Immutability is used to prevent accidental changes to the design.

is_placeholder_instance property

is_placeholder_instance: bool

A placeholder represents an element that does not have a specific path.

True if this NetlistElement instance represents a placeholder, False otherwise.

can_carry_signal property

can_carry_signal: bool

Whether this exact object is able to receive, pass or hold signal values.

True for ports (as they drive or receive values) and wires (as they pass the signals from driver to load ports) as well as their respective segments. False for instances and modules.

connections property

connections: Dict[str, Dict[int, WireSegmentPath]]

A dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port. Elements with no connection (i.e. the path is None) are excluded. In case these are needed, use Instance.get_connections() instead.

Example

{ 'port1': {1: WireSegmentPath('path/to/element1'), 2: WireSegmentPath('path/to/element2')}, 'port2': {1: WireSegmentPath('path/to/element3')} }

connection_str_paths property

connection_str_paths: Dict[str, Dict[int, str]]

Returns a dictionary mapping port names to their corresponding connection paths as strings.

The keys are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are the raw string paths.

Example

{ 'port1': {0: 'path.to.element1', 1: 'path.to.element2'}, 'port2': {0: 'path.to.element3'} }

ports property

A dictionary mapping port names to their corresponding Port objects.

The keys of the dictionary are the names of the ports. The values are Port objects representing the ports.

Returns:

input_ports property

input_ports: Tuple[Port[Instance], ...]

Returns a tuple of input ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as inputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the input ports.

output_ports property

output_ports: Tuple[Port[Instance], ...]

Returns a tuple of output ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as outputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the output ports.

has_unconnected_port_segments property

has_unconnected_port_segments: bool

Returns True if the instance has at least one unconnected port segment.

signals property

signals: Dict[str, SignalArray]

A dictionary with all signals currently present on all ports of this instance.

is_blackbox property

is_blackbox: bool

Flag indicating whether the instance represents neither a primitive element nor a module instance.

If True, this instance does not have a module definition, and is also not a basic component (i.e. a primitive gate instance) from the internal gate library, such as a gate or flip-flop.

y_width property

y_width: PositiveInt

Width of the gate, which is always 1 for gates that reduce N-bit inputs to 1 bit.

a_width property

a_width: PositiveInt

Width of the gate's A port.

b_width property

b_width: PositiveInt

Width of the gate's B port.

is_combinational property

is_combinational: bool

Whether instances of this gate are considered combinational gates.

True for combinational gates, such as AND gates or arithmetic gates. False for flip-flops and latches.

is_sequential property

is_sequential: bool

Whether instances of this gate are considered sequential gates.

False for combinational gates, such as AND gates or arithmetic gates. True for flip-flops and latches.

output_port property

output_port: Port[Instance]

The output port of the gate.

data_width property

data_width: int

The data width of this instance.

Defaults to the data width of the output port. Can be overwritten in extended classes.

In contrast to self.width, which is used for the creation and initialization, this property is linked to the data width of the output port. This property is useful when the data width of the output port can be changed.

input_port property

input_port: Port[Instance]

The input port of the gate.

a_signed property

a_signed: bool

The signedness of input port A.

truth_table property

truth_table: Dict[Signal, Signal]

A simple truth table as a dictionary.

This dictionary contains the input-output mapping for unary gates that evaluate bitwise (e.g. Buffer, NotGate). Not implemented for arithmetic gates (e.g. NegGate, PosGate).

change_mutability

change_mutability(is_now_locked: bool, recursive: bool = False) -> Self

Change the mutability status of this instance and optionally its ports.

This method allows setting whether this instance can be modified or not. If recursive is set to True, it also applies the same mutability status to all ports of this instance.

Parameters:

  • is_now_locked

    (bool) –

    The new mutability status for this instance.

  • recursive

    (bool, default: False ) –

    Whether to apply the change recursively to its ports. Defaults to False.

evaluate

evaluate() -> None

Evaluates the gate's output signal based on its input signals.

This method is called when the gate's input signals change, and it updates the gate's output signal accordingly.

all_connections

all_connections(
    include_unconnected: bool,
) -> Dict[str, Dict[int, WireSegmentPath]]

Returns a dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port.

Parameters:

  • include_unconnected

    (bool) –

    Whether to include unconnected ports in the result.

Returns:

model_post_init

model_post_init(__context: object) -> None

Initializes the gate's ports and connections.

This method is called after the gate's attributes have been initialized, and it sets up the gate's ports and connections.

connect

connect(
    port_name: str,
    ws_path: Optional[WireSegmentPath],
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add connections to the specified port of this instance.

This method can establish multiple connections if a range of indices is provided.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection(s) should be established.

  • ws_path

    (Optional[WireSegmentPath]) –

    The path of the wire segment that will be connected to this port. If None, the associated port (segment) remains unconnected.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

Raises:

  • ObjectLockedError

    If this instance is currently locked, and no connection can be made.

disconnect

disconnect(port_name: str, index: Optional[int] = None) -> None

Remove an existing connection from a specified port of this instance.

This method disconnects the wire segment at the given index within the specified port_name.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be removed.

  • index

    (Optional[int], default: None ) –

    The bit index within the port for this disconnection. Defaults to None, which completely disconnects the port.

Raises:

get_connection

get_connection(
    port_name: str, index: Optional[NonNegativeInt] = None
) -> Union[WireSegmentPath, Dict[int, WireSegmentPath], None]

Retrieve the connection path associated with a specified port and bit index.

If index is provided, this method returns the wire segment path connected to that specific bit within the port. Otherwise, it returns all connections for the given port as a dictionary mapping indices to WireSegmentPaths.

Parameters:

  • port_name

    (str) –

    The name of the port for which to retrieve the connection(s).

  • index

    (Optional[NonNegativeInt], default: None ) –

    The bit index within the port. Defaults to None.

Returns:

modify_connection

modify_connection(
    port_name: str, ws_path: WireSegmentPath, index: NonNegativeInt = 0
) -> None

Modify an existing connection within a specified port of this instance.

This method updates the wire segment path at the given index within the specified port_name. If the index does not exist yet, it is newly added, changing the width of the port.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be modified.

  • ws_path

    (WireSegmentPath) –

    The new wire segment path for this connection.

  • index

    (NonNegativeInt, default: 0 ) –

    The bit index within the port. Defaults to 0.

connect_modify

connect_modify(
    port_name: str,
    ws_path: WireSegmentPath,
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add a new connection or modify an existing one within the specified port of this instance.

If the connection already exists at the given index and port_name, it will be modified. Otherwise, a new connection is added.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be established or updated.

  • ws_path

    (WireSegmentPath) –

    The path of the wire segment that will be connected to this port.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

tie_port

tie_port(name: str, index: NonNegativeInt, sig_value: LogicLevel) -> None

Set a constant signal value for the specified port and bit index.

If the specified port does not exist, an error message is logged and the function returns False. Otherwise, the method tries to set the constant signal value for that port and returns True if successful.

Does not work for instance output ports, as they are always driven by their parent instances.

Parameters:

  • name

    (str) –

    The name of the port.

  • index

    (NonNegativeInt) –

    The bit index within the port.

  • sig_value

    (LogicLevel) –

    The constant signal value to be set ('0', '1', or 'Z').

Raises:

  • ObjectNotFoundError

    If no such port or port segment exists.

  • AlreadyConnectedError

    (raised by: PortSegment.tie_signal) If this segment is belongs to a load port and is already connected to a wire, from which it receives its value.

  • InvalidDirectionError

    (raised by: PortSegment.tie_signal) If this port segment belongs to an instance output port, which is driven by the instance inputs and the instance's internal logic.

  • InvalidSignalError

    (raised by: PortSegment.tie_signal) If an invalid value is provided.

has_tied_ports

has_tied_ports() -> bool

Checks the ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any ports of this instance are tied to constant values. False otherwise, i.e. all ports are connected to wires.

has_tied_inputs

has_tied_inputs() -> bool

Checks the input ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any input ports of this instance are tied to constant values. False otherwise, i.e. all input ports are connected to wires.

has_tied_outputs

has_tied_outputs() -> bool

Checks the output ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any output ports of this instance are tied to constant values. False otherwise, i.e. all output ports are connected to wires.

update_signedness

update_signedness(port_name: str) -> None

Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

Parameters:

  • port_name

    (str) –

    The name of the port, of which the signedness value is retrieved.

split

split() -> Dict[NonNegativeInt, Self]

Performs a bit-wise split on this instance.

If this instance supports splitting and has a data width of n bit, this method splits this instance into n 1-bit instances. This works for instances, where each output bit depends only on the corresponding input bit(s), e.g. an AND gate or a D-Flipflop.

Returns:

  • Dict[NonNegativeInt, Self]

    Dict[int, Instance]: An n-bit large dictionary, where each key conforms to a bit of the original instance, and each value is an 1-bit instance representing the corresponding "slice" of the original instance.

Raises:

  • SplittingUnsupportedError

    If this instance does not support splitting. Happens for any gate or instance whose behavior depends on the whole bus, and splitting would make it lose its meaning.

p2v

p2v(
    port: ANY_PORT,
    exclude_indices: Optional[List[int]] = None,
    include_indices: Optional[List[int]] = None,
) -> str

Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a Port object and converts them to their corresponding Verilog signal structure (p2v -> Port to Verilog signal syntax). For each segment of the port, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port is set to a constant, the corresponding constant wire segment placeholder is used instead. Port segments can be excluded from the conversion by providing a list of indices to the exclude_indices parameter, indicating which segments should be excluded from the conversion (e.g. segments that are known to be unconnected). Vice versa, only a certain subset of the port's segments may be converted to Verilog syntax, if include_indices is a given list of port indices. All indices not present in the list will be excluded from the conversion.

Parameters:

  • port

    (Port) –

    The Port object to convert.

  • exclude_indices

    (List[int], default: None ) –

    A list of indices to exclude from the conversion. Defaults to None.

  • include_indices

    (List[int], default: None ) –

    A list of indices (i.e. port slices) to include only for the conversion. Defaults to None.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

  • ObjectNotFoundError

    If the wire connected to a certain port segment could not be found.

  • UnsupportedOperationError

    If both exclude_indices and include_indices are specified. Only one of both may be given when calling this method.

ps2v

Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a PortSegment dictionary and converts them to their corresponding Verilog signal structure (ps2v -> PortSegment to Verilog signal syntax). For each segment, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port segment is set to a constant, the corresponding constant wire segment placeholder is used instead.

Parameters:

  • ps_dict

    (Dict[int, PortSegment]) –

    The PortSegment dictionary to convert. Each key (int) conforms to the index of the associated PortSegment object.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

set

set(
    port_name: str,
    new_signal: SignalOrLogicLevel,
    idx: Union[int, List[int]] = 0,
) -> None

Sets the signal on a port.

Parameters:

  • port_name

    (str) –

    The name of the port to set the signal on.

  • new_signal

    (Signal) –

    The new signal value.

  • idx

    (Union[int, List[int]], default: 0 ) –

    The index (or indices) to apply the given signal to. Can either be an integer (single index to set) or an iterable of integers (e.g. a list of indices). For every integer of the iterable the signal value of the corresponding port index is set to the given new_signal. Defaults to 0.

Example

from netlist_carpentry.utils.gate_factory import and_gate module = Module(name='m') a = module.create_port('a', 'input', width=6) instance = and_gate(module, 'inst', A=a)

This sets the value of bit 0 of port A to HIGH

instance.set('A', 1, 0) instance.ports['A'].signal_str 'xxxxx1'

This sets the value of bits 1, 3 and 5 of port A to LOW, leaving the other bits as they already are.

instance.set('A', 0, [1, 3, 5]) instance.ports['A'].signal_str '0x0x01'

get_result

get_result(s: Signal) -> Signal

Returns the result of this gate's operation for given Signal s.

This method is only implemented for bitwise evaluating gates (e.g. Buffer, NotGate). This method raises an UnsupportedOperationError if used on arithmetic gates (e.g. PosGate, NegGate).

For vector-level operations on full signal arrays, use :meth:get_result_vector instead.

Parameters:

  • s

    (Signal) –

    The Signal, i.e. the input operand.

Raises:

Returns:

  • Signal ( Signal ) –

    The result of this gate's operation on the given signals.

get_result_vector

get_result_vector(s: SignalArray) -> SignalArray

Returns the result of this reduction gate's operation for a full signal vector.

Reduces an N-bit :class:SignalArray to a 1-bit :class:SignalArray by applying :meth:reduce_operation across all bits using :func:functools.reduce.

Parameters:

Returns:

  • SignalArray ( SignalArray ) –

    A 1-bit SignalArray containing the reduction result.

signal_in

signal_in(idx: NonNegativeInt = 0) -> Signal

The input signal of the gate.

Returns:

  • Signal ( Signal ) –

    The input signal of the gate.

signal_out

signal_out() -> Signal

The output signal of the gate.

ReduceXnor

Bases: ReduceGate, BaseModel

A reduction XNOR gate.

A reduction XNOR gate performs a logical XNOR operation on all input signals. It produces a HIGH output signal if an even number of input signals are HIGH.

Methods:

  • change_mutability

    Change the mutability status of this instance and optionally its ports.

  • evaluate

    Evaluates the gate's output signal based on its input signals.

  • all_connections

    Returns a dictionary mapping port names to their corresponding connection paths.

  • model_post_init

    Initializes the gate's ports and connections.

  • connect

    Add connections to the specified port of this instance.

  • disconnect

    Remove an existing connection from a specified port of this instance.

  • get_connection

    Retrieve the connection path associated with a specified port and bit index.

  • modify_connection

    Modify an existing connection within a specified port of this instance.

  • connect_modify

    Add a new connection or modify an existing one within the specified port of this instance.

  • tie_port

    Set a constant signal value for the specified port and bit index.

  • has_tied_ports

    Checks the ports of this instance whether any are tied to constant values.

  • has_tied_inputs

    Checks the input ports of this instance whether any are tied to constant values.

  • has_tied_outputs

    Checks the output ports of this instance whether any are tied to constant values.

  • update_signedness

    Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

  • split

    Performs a bit-wise split on this instance.

  • p2v

    Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

  • ps2v

    Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

  • set

    Sets the signal on a port.

  • get_result

    Returns the result of this gate's operation for given Signal s.

  • get_result_vector

    Returns the result of this reduction gate's operation for a full signal vector.

  • signal_in

    The input signal of the gate.

  • signal_out

    The output signal of the gate.

Attributes:

reduce_operation property

reduce_operation: Callable[[Signal, Signal], Signal]

Provides a lambda function for this gate.

The lambda function takes two signals and executes this gate's operation on both of them. In junction with functools.reduce(), this reduces the input signal array down to a single bit by concatenating the operation of this gate bit-by-bit.

For a reduction XNOR gate, the output signal is HIGH if an even number of input signals are HIGH. If an odd number of input signals are HIGH or any input signal is undefined, the output signal will be LOW or undefined, respectively.

name instance-attribute

name: str

The name of the element.

!!! Do not modify this variable after instantiating it. Use NetlistElement.set_name() instead. Modifying this variable might lead to inconsistencies later on.

metadata class-attribute instance-attribute

Metadata of a netlist element.

Can be user-defined, or e. g. by Yosys (such as src for the HDL source). Is also grouped by categories, i.e. all metadata from Yosys can be accessed via Module.metadata["yosys"], or via Module.metadata.yosys, which both return a dictionary of all metadata. Read the documentation of MetaDataMixin for more information.

path property

Returns the InstancePath of the netlist element.

The InstancePath object is constructed using the element's type and its raw hierarchical path.

Returns:

  • InstancePath ( InstancePath ) –

    The hierarchical path of the netlist element.

type property

type: EType

The type of the element, which is an instance.

hierarchy_level property

hierarchy_level: int

The level of hierarchy of the element in the design.

The hierarchy level is the number of separators in the element's raw path. For example, a top-level instance has a hierarchy level of 0, while a direct submodule instance has a hierarchy level of 1.

Returns:

  • int ( int ) –

    The hierarchy level of the element.

has_parent property

has_parent: bool

Whether this object has a parent.

circuit property

circuit: 'Circuit'

The circuit object to which this netlist element belongs to.

  • For a module, returns the circuit to which the module belongs.
  • For any other netlist element, recursively returns the circuit of the parent, which ultimately leads to a module, to which the netlist element belongs.

Raises:

  • ParentNotFoundError

    If a parent cannot be resolved somewhere in the hierarchical chain.

  • ObjectNotFoundError

    If for a module no circuit is set.

has_circuit property

has_circuit: bool

Whether this netlist element has a defined circuit it belongs to.

Tries to access self.circuit and returns whether the call was successful. Can be used instead of a try-except clause around the call to NetlistElement.circuit.

locked property

locked: bool

True if this NetlistElement instance is locked (i.e. it is currently structurally unchangeable), False if it is mutable.

Can be changed via NetlistElement.change_mutability(bool).

Immutability is used to prevent accidental changes to the design.

is_placeholder_instance property

is_placeholder_instance: bool

A placeholder represents an element that does not have a specific path.

True if this NetlistElement instance represents a placeholder, False otherwise.

can_carry_signal property

can_carry_signal: bool

Whether this exact object is able to receive, pass or hold signal values.

True for ports (as they drive or receive values) and wires (as they pass the signals from driver to load ports) as well as their respective segments. False for instances and modules.

connections property

connections: Dict[str, Dict[int, WireSegmentPath]]

A dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port. Elements with no connection (i.e. the path is None) are excluded. In case these are needed, use Instance.get_connections() instead.

Example

{ 'port1': {1: WireSegmentPath('path/to/element1'), 2: WireSegmentPath('path/to/element2')}, 'port2': {1: WireSegmentPath('path/to/element3')} }

connection_str_paths property

connection_str_paths: Dict[str, Dict[int, str]]

Returns a dictionary mapping port names to their corresponding connection paths as strings.

The keys are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are the raw string paths.

Example

{ 'port1': {0: 'path.to.element1', 1: 'path.to.element2'}, 'port2': {0: 'path.to.element3'} }

ports property

A dictionary mapping port names to their corresponding Port objects.

The keys of the dictionary are the names of the ports. The values are Port objects representing the ports.

Returns:

input_ports property

input_ports: Tuple[Port[Instance], ...]

Returns a tuple of input ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as inputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the input ports.

output_ports property

output_ports: Tuple[Port[Instance], ...]

Returns a tuple of output ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as outputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the output ports.

has_unconnected_port_segments property

has_unconnected_port_segments: bool

Returns True if the instance has at least one unconnected port segment.

signals property

signals: Dict[str, SignalArray]

A dictionary with all signals currently present on all ports of this instance.

is_blackbox property

is_blackbox: bool

Flag indicating whether the instance represents neither a primitive element nor a module instance.

If True, this instance does not have a module definition, and is also not a basic component (i.e. a primitive gate instance) from the internal gate library, such as a gate or flip-flop.

y_width property

y_width: PositiveInt

Width of the gate, which is always 1 for gates that reduce N-bit inputs to 1 bit.

a_width property

a_width: PositiveInt

Width of the gate's A port.

b_width property

b_width: PositiveInt

Width of the gate's B port.

is_combinational property

is_combinational: bool

Whether instances of this gate are considered combinational gates.

True for combinational gates, such as AND gates or arithmetic gates. False for flip-flops and latches.

is_sequential property

is_sequential: bool

Whether instances of this gate are considered sequential gates.

False for combinational gates, such as AND gates or arithmetic gates. True for flip-flops and latches.

output_port property

output_port: Port[Instance]

The output port of the gate.

data_width property

data_width: int

The data width of this instance.

Defaults to the data width of the output port. Can be overwritten in extended classes.

In contrast to self.width, which is used for the creation and initialization, this property is linked to the data width of the output port. This property is useful when the data width of the output port can be changed.

input_port property

input_port: Port[Instance]

The input port of the gate.

a_signed property

a_signed: bool

The signedness of input port A.

truth_table property

truth_table: Dict[Signal, Signal]

A simple truth table as a dictionary.

This dictionary contains the input-output mapping for unary gates that evaluate bitwise (e.g. Buffer, NotGate). Not implemented for arithmetic gates (e.g. NegGate, PosGate).

change_mutability

change_mutability(is_now_locked: bool, recursive: bool = False) -> Self

Change the mutability status of this instance and optionally its ports.

This method allows setting whether this instance can be modified or not. If recursive is set to True, it also applies the same mutability status to all ports of this instance.

Parameters:

  • is_now_locked

    (bool) –

    The new mutability status for this instance.

  • recursive

    (bool, default: False ) –

    Whether to apply the change recursively to its ports. Defaults to False.

evaluate

evaluate() -> None

Evaluates the gate's output signal based on its input signals.

This method is called when the gate's input signals change, and it updates the gate's output signal accordingly.

all_connections

all_connections(
    include_unconnected: bool,
) -> Dict[str, Dict[int, WireSegmentPath]]

Returns a dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port.

Parameters:

  • include_unconnected

    (bool) –

    Whether to include unconnected ports in the result.

Returns:

model_post_init

model_post_init(__context: object) -> None

Initializes the gate's ports and connections.

This method is called after the gate's attributes have been initialized, and it sets up the gate's ports and connections.

connect

connect(
    port_name: str,
    ws_path: Optional[WireSegmentPath],
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add connections to the specified port of this instance.

This method can establish multiple connections if a range of indices is provided.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection(s) should be established.

  • ws_path

    (Optional[WireSegmentPath]) –

    The path of the wire segment that will be connected to this port. If None, the associated port (segment) remains unconnected.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

Raises:

  • ObjectLockedError

    If this instance is currently locked, and no connection can be made.

disconnect

disconnect(port_name: str, index: Optional[int] = None) -> None

Remove an existing connection from a specified port of this instance.

This method disconnects the wire segment at the given index within the specified port_name.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be removed.

  • index

    (Optional[int], default: None ) –

    The bit index within the port for this disconnection. Defaults to None, which completely disconnects the port.

Raises:

get_connection

get_connection(
    port_name: str, index: Optional[NonNegativeInt] = None
) -> Union[WireSegmentPath, Dict[int, WireSegmentPath], None]

Retrieve the connection path associated with a specified port and bit index.

If index is provided, this method returns the wire segment path connected to that specific bit within the port. Otherwise, it returns all connections for the given port as a dictionary mapping indices to WireSegmentPaths.

Parameters:

  • port_name

    (str) –

    The name of the port for which to retrieve the connection(s).

  • index

    (Optional[NonNegativeInt], default: None ) –

    The bit index within the port. Defaults to None.

Returns:

modify_connection

modify_connection(
    port_name: str, ws_path: WireSegmentPath, index: NonNegativeInt = 0
) -> None

Modify an existing connection within a specified port of this instance.

This method updates the wire segment path at the given index within the specified port_name. If the index does not exist yet, it is newly added, changing the width of the port.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be modified.

  • ws_path

    (WireSegmentPath) –

    The new wire segment path for this connection.

  • index

    (NonNegativeInt, default: 0 ) –

    The bit index within the port. Defaults to 0.

connect_modify

connect_modify(
    port_name: str,
    ws_path: WireSegmentPath,
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add a new connection or modify an existing one within the specified port of this instance.

If the connection already exists at the given index and port_name, it will be modified. Otherwise, a new connection is added.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be established or updated.

  • ws_path

    (WireSegmentPath) –

    The path of the wire segment that will be connected to this port.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

tie_port

tie_port(name: str, index: NonNegativeInt, sig_value: LogicLevel) -> None

Set a constant signal value for the specified port and bit index.

If the specified port does not exist, an error message is logged and the function returns False. Otherwise, the method tries to set the constant signal value for that port and returns True if successful.

Does not work for instance output ports, as they are always driven by their parent instances.

Parameters:

  • name

    (str) –

    The name of the port.

  • index

    (NonNegativeInt) –

    The bit index within the port.

  • sig_value

    (LogicLevel) –

    The constant signal value to be set ('0', '1', or 'Z').

Raises:

  • ObjectNotFoundError

    If no such port or port segment exists.

  • AlreadyConnectedError

    (raised by: PortSegment.tie_signal) If this segment is belongs to a load port and is already connected to a wire, from which it receives its value.

  • InvalidDirectionError

    (raised by: PortSegment.tie_signal) If this port segment belongs to an instance output port, which is driven by the instance inputs and the instance's internal logic.

  • InvalidSignalError

    (raised by: PortSegment.tie_signal) If an invalid value is provided.

has_tied_ports

has_tied_ports() -> bool

Checks the ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any ports of this instance are tied to constant values. False otherwise, i.e. all ports are connected to wires.

has_tied_inputs

has_tied_inputs() -> bool

Checks the input ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any input ports of this instance are tied to constant values. False otherwise, i.e. all input ports are connected to wires.

has_tied_outputs

has_tied_outputs() -> bool

Checks the output ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any output ports of this instance are tied to constant values. False otherwise, i.e. all output ports are connected to wires.

update_signedness

update_signedness(port_name: str) -> None

Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

Parameters:

  • port_name

    (str) –

    The name of the port, of which the signedness value is retrieved.

split

split() -> Dict[NonNegativeInt, Self]

Performs a bit-wise split on this instance.

If this instance supports splitting and has a data width of n bit, this method splits this instance into n 1-bit instances. This works for instances, where each output bit depends only on the corresponding input bit(s), e.g. an AND gate or a D-Flipflop.

Returns:

  • Dict[NonNegativeInt, Self]

    Dict[int, Instance]: An n-bit large dictionary, where each key conforms to a bit of the original instance, and each value is an 1-bit instance representing the corresponding "slice" of the original instance.

Raises:

  • SplittingUnsupportedError

    If this instance does not support splitting. Happens for any gate or instance whose behavior depends on the whole bus, and splitting would make it lose its meaning.

p2v

p2v(
    port: ANY_PORT,
    exclude_indices: Optional[List[int]] = None,
    include_indices: Optional[List[int]] = None,
) -> str

Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a Port object and converts them to their corresponding Verilog signal structure (p2v -> Port to Verilog signal syntax). For each segment of the port, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port is set to a constant, the corresponding constant wire segment placeholder is used instead. Port segments can be excluded from the conversion by providing a list of indices to the exclude_indices parameter, indicating which segments should be excluded from the conversion (e.g. segments that are known to be unconnected). Vice versa, only a certain subset of the port's segments may be converted to Verilog syntax, if include_indices is a given list of port indices. All indices not present in the list will be excluded from the conversion.

Parameters:

  • port

    (Port) –

    The Port object to convert.

  • exclude_indices

    (List[int], default: None ) –

    A list of indices to exclude from the conversion. Defaults to None.

  • include_indices

    (List[int], default: None ) –

    A list of indices (i.e. port slices) to include only for the conversion. Defaults to None.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

  • ObjectNotFoundError

    If the wire connected to a certain port segment could not be found.

  • UnsupportedOperationError

    If both exclude_indices and include_indices are specified. Only one of both may be given when calling this method.

ps2v

Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a PortSegment dictionary and converts them to their corresponding Verilog signal structure (ps2v -> PortSegment to Verilog signal syntax). For each segment, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port segment is set to a constant, the corresponding constant wire segment placeholder is used instead.

Parameters:

  • ps_dict

    (Dict[int, PortSegment]) –

    The PortSegment dictionary to convert. Each key (int) conforms to the index of the associated PortSegment object.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

set

set(
    port_name: str,
    new_signal: SignalOrLogicLevel,
    idx: Union[int, List[int]] = 0,
) -> None

Sets the signal on a port.

Parameters:

  • port_name

    (str) –

    The name of the port to set the signal on.

  • new_signal

    (Signal) –

    The new signal value.

  • idx

    (Union[int, List[int]], default: 0 ) –

    The index (or indices) to apply the given signal to. Can either be an integer (single index to set) or an iterable of integers (e.g. a list of indices). For every integer of the iterable the signal value of the corresponding port index is set to the given new_signal. Defaults to 0.

Example

from netlist_carpentry.utils.gate_factory import and_gate module = Module(name='m') a = module.create_port('a', 'input', width=6) instance = and_gate(module, 'inst', A=a)

This sets the value of bit 0 of port A to HIGH

instance.set('A', 1, 0) instance.ports['A'].signal_str 'xxxxx1'

This sets the value of bits 1, 3 and 5 of port A to LOW, leaving the other bits as they already are.

instance.set('A', 0, [1, 3, 5]) instance.ports['A'].signal_str '0x0x01'

get_result

get_result(s: Signal) -> Signal

Returns the result of this gate's operation for given Signal s.

This method is only implemented for bitwise evaluating gates (e.g. Buffer, NotGate). This method raises an UnsupportedOperationError if used on arithmetic gates (e.g. PosGate, NegGate).

For vector-level operations on full signal arrays, use :meth:get_result_vector instead.

Parameters:

  • s

    (Signal) –

    The Signal, i.e. the input operand.

Raises:

Returns:

  • Signal ( Signal ) –

    The result of this gate's operation on the given signals.

get_result_vector

get_result_vector(s: SignalArray) -> SignalArray

Returns the result of this reduction gate's operation for a full signal vector.

Reduces an N-bit :class:SignalArray to a 1-bit :class:SignalArray by applying :meth:reduce_operation across all bits using :func:functools.reduce.

Parameters:

Returns:

  • SignalArray ( SignalArray ) –

    A 1-bit SignalArray containing the reduction result.

signal_in

signal_in(idx: NonNegativeInt = 0) -> Signal

The input signal of the gate.

Returns:

  • Signal ( Signal ) –

    The input signal of the gate.

signal_out

signal_out() -> Signal

The output signal of the gate.

LogicNot

Bases: ReduceGate, BaseModel

A logic not gate.

A logic not gate performs a logical not operation on all input signals. It produces a HIGH output signal if all input signals are LOW. The output is LOW, if any input signal is HIGH. If there are undefined bits, the result is also UNDEFINED.

Methods:

  • change_mutability

    Change the mutability status of this instance and optionally its ports.

  • evaluate

    Evaluates the gate's output signal based on its input signals.

  • all_connections

    Returns a dictionary mapping port names to their corresponding connection paths.

  • model_post_init

    Initializes the gate's ports and connections.

  • connect

    Add connections to the specified port of this instance.

  • disconnect

    Remove an existing connection from a specified port of this instance.

  • get_connection

    Retrieve the connection path associated with a specified port and bit index.

  • modify_connection

    Modify an existing connection within a specified port of this instance.

  • connect_modify

    Add a new connection or modify an existing one within the specified port of this instance.

  • tie_port

    Set a constant signal value for the specified port and bit index.

  • has_tied_ports

    Checks the ports of this instance whether any are tied to constant values.

  • has_tied_inputs

    Checks the input ports of this instance whether any are tied to constant values.

  • has_tied_outputs

    Checks the output ports of this instance whether any are tied to constant values.

  • update_signedness

    Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

  • split

    Performs a bit-wise split on this instance.

  • p2v

    Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

  • ps2v

    Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

  • set

    Sets the signal on a port.

  • get_result

    Returns the result of this gate's operation for given Signal s.

  • signal_in

    The input signal of the gate.

  • signal_out

    The output signal of the gate.

Attributes:

reduce_operation property

reduce_operation: Callable[[Signal, Signal], Signal]

Returns the raw reduction, without the inversion!

Provides a lambda function for this gate.

The lambda function takes two signals and executes this gate's operation on both of them. In junction with functools.reduce(), this reduces the input signal array down to a single bit by concatenating the operation of this gate bit-by-bit.

For a logic not gate, the output signal is HIGH if all input signals are LOW. The output is LOW, if any input signal is HIGH. If there are undefined bits, the result is also UNDEFINED.

name instance-attribute

name: str

The name of the element.

!!! Do not modify this variable after instantiating it. Use NetlistElement.set_name() instead. Modifying this variable might lead to inconsistencies later on.

metadata class-attribute instance-attribute

Metadata of a netlist element.

Can be user-defined, or e. g. by Yosys (such as src for the HDL source). Is also grouped by categories, i.e. all metadata from Yosys can be accessed via Module.metadata["yosys"], or via Module.metadata.yosys, which both return a dictionary of all metadata. Read the documentation of MetaDataMixin for more information.

path property

Returns the InstancePath of the netlist element.

The InstancePath object is constructed using the element's type and its raw hierarchical path.

Returns:

  • InstancePath ( InstancePath ) –

    The hierarchical path of the netlist element.

type property

type: EType

The type of the element, which is an instance.

hierarchy_level property

hierarchy_level: int

The level of hierarchy of the element in the design.

The hierarchy level is the number of separators in the element's raw path. For example, a top-level instance has a hierarchy level of 0, while a direct submodule instance has a hierarchy level of 1.

Returns:

  • int ( int ) –

    The hierarchy level of the element.

has_parent property

has_parent: bool

Whether this object has a parent.

circuit property

circuit: 'Circuit'

The circuit object to which this netlist element belongs to.

  • For a module, returns the circuit to which the module belongs.
  • For any other netlist element, recursively returns the circuit of the parent, which ultimately leads to a module, to which the netlist element belongs.

Raises:

  • ParentNotFoundError

    If a parent cannot be resolved somewhere in the hierarchical chain.

  • ObjectNotFoundError

    If for a module no circuit is set.

has_circuit property

has_circuit: bool

Whether this netlist element has a defined circuit it belongs to.

Tries to access self.circuit and returns whether the call was successful. Can be used instead of a try-except clause around the call to NetlistElement.circuit.

locked property

locked: bool

True if this NetlistElement instance is locked (i.e. it is currently structurally unchangeable), False if it is mutable.

Can be changed via NetlistElement.change_mutability(bool).

Immutability is used to prevent accidental changes to the design.

is_placeholder_instance property

is_placeholder_instance: bool

A placeholder represents an element that does not have a specific path.

True if this NetlistElement instance represents a placeholder, False otherwise.

can_carry_signal property

can_carry_signal: bool

Whether this exact object is able to receive, pass or hold signal values.

True for ports (as they drive or receive values) and wires (as they pass the signals from driver to load ports) as well as their respective segments. False for instances and modules.

connections property

connections: Dict[str, Dict[int, WireSegmentPath]]

A dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port. Elements with no connection (i.e. the path is None) are excluded. In case these are needed, use Instance.get_connections() instead.

Example

{ 'port1': {1: WireSegmentPath('path/to/element1'), 2: WireSegmentPath('path/to/element2')}, 'port2': {1: WireSegmentPath('path/to/element3')} }

connection_str_paths property

connection_str_paths: Dict[str, Dict[int, str]]

Returns a dictionary mapping port names to their corresponding connection paths as strings.

The keys are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are the raw string paths.

Example

{ 'port1': {0: 'path.to.element1', 1: 'path.to.element2'}, 'port2': {0: 'path.to.element3'} }

ports property

A dictionary mapping port names to their corresponding Port objects.

The keys of the dictionary are the names of the ports. The values are Port objects representing the ports.

Returns:

input_ports property

input_ports: Tuple[Port[Instance], ...]

Returns a tuple of input ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as inputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the input ports.

output_ports property

output_ports: Tuple[Port[Instance], ...]

Returns a tuple of output ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as outputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the output ports.

has_unconnected_port_segments property

has_unconnected_port_segments: bool

Returns True if the instance has at least one unconnected port segment.

signals property

signals: Dict[str, SignalArray]

A dictionary with all signals currently present on all ports of this instance.

is_blackbox property

is_blackbox: bool

Flag indicating whether the instance represents neither a primitive element nor a module instance.

If True, this instance does not have a module definition, and is also not a basic component (i.e. a primitive gate instance) from the internal gate library, such as a gate or flip-flop.

y_width property

y_width: PositiveInt

Width of the gate, which is always 1 for gates that reduce N-bit inputs to 1 bit.

a_width property

a_width: PositiveInt

Width of the gate's A port.

b_width property

b_width: PositiveInt

Width of the gate's B port.

is_combinational property

is_combinational: bool

Whether instances of this gate are considered combinational gates.

True for combinational gates, such as AND gates or arithmetic gates. False for flip-flops and latches.

is_sequential property

is_sequential: bool

Whether instances of this gate are considered sequential gates.

False for combinational gates, such as AND gates or arithmetic gates. True for flip-flops and latches.

output_port property

output_port: Port[Instance]

The output port of the gate.

data_width property

data_width: int

The data width of this instance.

Defaults to the data width of the output port. Can be overwritten in extended classes.

In contrast to self.width, which is used for the creation and initialization, this property is linked to the data width of the output port. This property is useful when the data width of the output port can be changed.

input_port property

input_port: Port[Instance]

The input port of the gate.

a_signed property

a_signed: bool

The signedness of input port A.

truth_table property

truth_table: Dict[Signal, Signal]

A simple truth table as a dictionary.

This dictionary contains the input-output mapping for unary gates that evaluate bitwise (e.g. Buffer, NotGate). Not implemented for arithmetic gates (e.g. NegGate, PosGate).

change_mutability

change_mutability(is_now_locked: bool, recursive: bool = False) -> Self

Change the mutability status of this instance and optionally its ports.

This method allows setting whether this instance can be modified or not. If recursive is set to True, it also applies the same mutability status to all ports of this instance.

Parameters:

  • is_now_locked

    (bool) –

    The new mutability status for this instance.

  • recursive

    (bool, default: False ) –

    Whether to apply the change recursively to its ports. Defaults to False.

evaluate

evaluate() -> None

Evaluates the gate's output signal based on its input signals.

This method is called when the gate's input signals change, and it updates the gate's output signal accordingly.

all_connections

all_connections(
    include_unconnected: bool,
) -> Dict[str, Dict[int, WireSegmentPath]]

Returns a dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port.

Parameters:

  • include_unconnected

    (bool) –

    Whether to include unconnected ports in the result.

Returns:

model_post_init

model_post_init(__context: object) -> None

Initializes the gate's ports and connections.

This method is called after the gate's attributes have been initialized, and it sets up the gate's ports and connections.

connect

connect(
    port_name: str,
    ws_path: Optional[WireSegmentPath],
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add connections to the specified port of this instance.

This method can establish multiple connections if a range of indices is provided.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection(s) should be established.

  • ws_path

    (Optional[WireSegmentPath]) –

    The path of the wire segment that will be connected to this port. If None, the associated port (segment) remains unconnected.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

Raises:

  • ObjectLockedError

    If this instance is currently locked, and no connection can be made.

disconnect

disconnect(port_name: str, index: Optional[int] = None) -> None

Remove an existing connection from a specified port of this instance.

This method disconnects the wire segment at the given index within the specified port_name.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be removed.

  • index

    (Optional[int], default: None ) –

    The bit index within the port for this disconnection. Defaults to None, which completely disconnects the port.

Raises:

get_connection

get_connection(
    port_name: str, index: Optional[NonNegativeInt] = None
) -> Union[WireSegmentPath, Dict[int, WireSegmentPath], None]

Retrieve the connection path associated with a specified port and bit index.

If index is provided, this method returns the wire segment path connected to that specific bit within the port. Otherwise, it returns all connections for the given port as a dictionary mapping indices to WireSegmentPaths.

Parameters:

  • port_name

    (str) –

    The name of the port for which to retrieve the connection(s).

  • index

    (Optional[NonNegativeInt], default: None ) –

    The bit index within the port. Defaults to None.

Returns:

modify_connection

modify_connection(
    port_name: str, ws_path: WireSegmentPath, index: NonNegativeInt = 0
) -> None

Modify an existing connection within a specified port of this instance.

This method updates the wire segment path at the given index within the specified port_name. If the index does not exist yet, it is newly added, changing the width of the port.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be modified.

  • ws_path

    (WireSegmentPath) –

    The new wire segment path for this connection.

  • index

    (NonNegativeInt, default: 0 ) –

    The bit index within the port. Defaults to 0.

connect_modify

connect_modify(
    port_name: str,
    ws_path: WireSegmentPath,
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add a new connection or modify an existing one within the specified port of this instance.

If the connection already exists at the given index and port_name, it will be modified. Otherwise, a new connection is added.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be established or updated.

  • ws_path

    (WireSegmentPath) –

    The path of the wire segment that will be connected to this port.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

tie_port

tie_port(name: str, index: NonNegativeInt, sig_value: LogicLevel) -> None

Set a constant signal value for the specified port and bit index.

If the specified port does not exist, an error message is logged and the function returns False. Otherwise, the method tries to set the constant signal value for that port and returns True if successful.

Does not work for instance output ports, as they are always driven by their parent instances.

Parameters:

  • name

    (str) –

    The name of the port.

  • index

    (NonNegativeInt) –

    The bit index within the port.

  • sig_value

    (LogicLevel) –

    The constant signal value to be set ('0', '1', or 'Z').

Raises:

  • ObjectNotFoundError

    If no such port or port segment exists.

  • AlreadyConnectedError

    (raised by: PortSegment.tie_signal) If this segment is belongs to a load port and is already connected to a wire, from which it receives its value.

  • InvalidDirectionError

    (raised by: PortSegment.tie_signal) If this port segment belongs to an instance output port, which is driven by the instance inputs and the instance's internal logic.

  • InvalidSignalError

    (raised by: PortSegment.tie_signal) If an invalid value is provided.

has_tied_ports

has_tied_ports() -> bool

Checks the ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any ports of this instance are tied to constant values. False otherwise, i.e. all ports are connected to wires.

has_tied_inputs

has_tied_inputs() -> bool

Checks the input ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any input ports of this instance are tied to constant values. False otherwise, i.e. all input ports are connected to wires.

has_tied_outputs

has_tied_outputs() -> bool

Checks the output ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any output ports of this instance are tied to constant values. False otherwise, i.e. all output ports are connected to wires.

update_signedness

update_signedness(port_name: str) -> None

Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

Parameters:

  • port_name

    (str) –

    The name of the port, of which the signedness value is retrieved.

split

split() -> Dict[NonNegativeInt, Self]

Performs a bit-wise split on this instance.

If this instance supports splitting and has a data width of n bit, this method splits this instance into n 1-bit instances. This works for instances, where each output bit depends only on the corresponding input bit(s), e.g. an AND gate or a D-Flipflop.

Returns:

  • Dict[NonNegativeInt, Self]

    Dict[int, Instance]: An n-bit large dictionary, where each key conforms to a bit of the original instance, and each value is an 1-bit instance representing the corresponding "slice" of the original instance.

Raises:

  • SplittingUnsupportedError

    If this instance does not support splitting. Happens for any gate or instance whose behavior depends on the whole bus, and splitting would make it lose its meaning.

p2v

p2v(
    port: ANY_PORT,
    exclude_indices: Optional[List[int]] = None,
    include_indices: Optional[List[int]] = None,
) -> str

Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a Port object and converts them to their corresponding Verilog signal structure (p2v -> Port to Verilog signal syntax). For each segment of the port, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port is set to a constant, the corresponding constant wire segment placeholder is used instead. Port segments can be excluded from the conversion by providing a list of indices to the exclude_indices parameter, indicating which segments should be excluded from the conversion (e.g. segments that are known to be unconnected). Vice versa, only a certain subset of the port's segments may be converted to Verilog syntax, if include_indices is a given list of port indices. All indices not present in the list will be excluded from the conversion.

Parameters:

  • port

    (Port) –

    The Port object to convert.

  • exclude_indices

    (List[int], default: None ) –

    A list of indices to exclude from the conversion. Defaults to None.

  • include_indices

    (List[int], default: None ) –

    A list of indices (i.e. port slices) to include only for the conversion. Defaults to None.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

  • ObjectNotFoundError

    If the wire connected to a certain port segment could not be found.

  • UnsupportedOperationError

    If both exclude_indices and include_indices are specified. Only one of both may be given when calling this method.

ps2v

Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a PortSegment dictionary and converts them to their corresponding Verilog signal structure (ps2v -> PortSegment to Verilog signal syntax). For each segment, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port segment is set to a constant, the corresponding constant wire segment placeholder is used instead.

Parameters:

  • ps_dict

    (Dict[int, PortSegment]) –

    The PortSegment dictionary to convert. Each key (int) conforms to the index of the associated PortSegment object.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

set

set(
    port_name: str,
    new_signal: SignalOrLogicLevel,
    idx: Union[int, List[int]] = 0,
) -> None

Sets the signal on a port.

Parameters:

  • port_name

    (str) –

    The name of the port to set the signal on.

  • new_signal

    (Signal) –

    The new signal value.

  • idx

    (Union[int, List[int]], default: 0 ) –

    The index (or indices) to apply the given signal to. Can either be an integer (single index to set) or an iterable of integers (e.g. a list of indices). For every integer of the iterable the signal value of the corresponding port index is set to the given new_signal. Defaults to 0.

Example

from netlist_carpentry.utils.gate_factory import and_gate module = Module(name='m') a = module.create_port('a', 'input', width=6) instance = and_gate(module, 'inst', A=a)

This sets the value of bit 0 of port A to HIGH

instance.set('A', 1, 0) instance.ports['A'].signal_str 'xxxxx1'

This sets the value of bits 1, 3 and 5 of port A to LOW, leaving the other bits as they already are.

instance.set('A', 0, [1, 3, 5]) instance.ports['A'].signal_str '0x0x01'

get_result

get_result(s: Signal) -> Signal

Returns the result of this gate's operation for given Signal s.

This method is only implemented for bitwise evaluating gates (e.g. Buffer, NotGate). This method raises an UnsupportedOperationError if used on arithmetic gates (e.g. PosGate, NegGate).

For vector-level operations on full signal arrays, use :meth:get_result_vector instead.

Parameters:

  • s

    (Signal) –

    The Signal, i.e. the input operand.

Raises:

Returns:

  • Signal ( Signal ) –

    The result of this gate's operation on the given signals.

signal_in

signal_in(idx: NonNegativeInt = 0) -> Signal

The input signal of the gate.

Returns:

  • Signal ( Signal ) –

    The input signal of the gate.

signal_out

signal_out() -> Signal

The output signal of the gate.

AndGate

Bases: BinaryGate, BaseModel

An AND gate.

An AND gate is a gate that produces a HIGH output signal only if both its input signals are HIGH. Otherwise, it produces a LOW output signal.

Methods:

  • change_mutability

    Change the mutability status of this instance and optionally its ports.

  • evaluate

    Evaluates the gate's output signal based on its input signals.

  • all_connections

    Returns a dictionary mapping port names to their corresponding connection paths.

  • model_post_init

    Initializes the gate's ports and connections.

  • connect

    Add connections to the specified port of this instance.

  • disconnect

    Remove an existing connection from a specified port of this instance.

  • get_connection

    Retrieve the connection path associated with a specified port and bit index.

  • modify_connection

    Modify an existing connection within a specified port of this instance.

  • connect_modify

    Add a new connection or modify an existing one within the specified port of this instance.

  • tie_port

    Set a constant signal value for the specified port and bit index.

  • has_tied_ports

    Checks the ports of this instance whether any are tied to constant values.

  • has_tied_inputs

    Checks the input ports of this instance whether any are tied to constant values.

  • has_tied_outputs

    Checks the output ports of this instance whether any are tied to constant values.

  • update_signedness

    Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

  • split

    Performs a bit-wise split on this instance.

  • p2v

    Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

  • ps2v

    Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

  • set

    Sets the signal on a port.

  • get_result_vector

    Returns the result of this gate's operation for full signal vectors.

  • signals_in

    The input signals of the gate.

  • signal_out

    The output signal of the gate.

Attributes:

name instance-attribute

name: str

The name of the element.

!!! Do not modify this variable after instantiating it. Use NetlistElement.set_name() instead. Modifying this variable might lead to inconsistencies later on.

metadata class-attribute instance-attribute

Metadata of a netlist element.

Can be user-defined, or e. g. by Yosys (such as src for the HDL source). Is also grouped by categories, i.e. all metadata from Yosys can be accessed via Module.metadata["yosys"], or via Module.metadata.yosys, which both return a dictionary of all metadata. Read the documentation of MetaDataMixin for more information.

path property

Returns the InstancePath of the netlist element.

The InstancePath object is constructed using the element's type and its raw hierarchical path.

Returns:

  • InstancePath ( InstancePath ) –

    The hierarchical path of the netlist element.

type property

type: EType

The type of the element, which is an instance.

hierarchy_level property

hierarchy_level: int

The level of hierarchy of the element in the design.

The hierarchy level is the number of separators in the element's raw path. For example, a top-level instance has a hierarchy level of 0, while a direct submodule instance has a hierarchy level of 1.

Returns:

  • int ( int ) –

    The hierarchy level of the element.

has_parent property

has_parent: bool

Whether this object has a parent.

circuit property

circuit: 'Circuit'

The circuit object to which this netlist element belongs to.

  • For a module, returns the circuit to which the module belongs.
  • For any other netlist element, recursively returns the circuit of the parent, which ultimately leads to a module, to which the netlist element belongs.

Raises:

  • ParentNotFoundError

    If a parent cannot be resolved somewhere in the hierarchical chain.

  • ObjectNotFoundError

    If for a module no circuit is set.

has_circuit property

has_circuit: bool

Whether this netlist element has a defined circuit it belongs to.

Tries to access self.circuit and returns whether the call was successful. Can be used instead of a try-except clause around the call to NetlistElement.circuit.

locked property

locked: bool

True if this NetlistElement instance is locked (i.e. it is currently structurally unchangeable), False if it is mutable.

Can be changed via NetlistElement.change_mutability(bool).

Immutability is used to prevent accidental changes to the design.

is_placeholder_instance property

is_placeholder_instance: bool

A placeholder represents an element that does not have a specific path.

True if this NetlistElement instance represents a placeholder, False otherwise.

can_carry_signal property

can_carry_signal: bool

Whether this exact object is able to receive, pass or hold signal values.

True for ports (as they drive or receive values) and wires (as they pass the signals from driver to load ports) as well as their respective segments. False for instances and modules.

connections property

connections: Dict[str, Dict[int, WireSegmentPath]]

A dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port. Elements with no connection (i.e. the path is None) are excluded. In case these are needed, use Instance.get_connections() instead.

Example

{ 'port1': {1: WireSegmentPath('path/to/element1'), 2: WireSegmentPath('path/to/element2')}, 'port2': {1: WireSegmentPath('path/to/element3')} }

connection_str_paths property

connection_str_paths: Dict[str, Dict[int, str]]

Returns a dictionary mapping port names to their corresponding connection paths as strings.

The keys are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are the raw string paths.

Example

{ 'port1': {0: 'path.to.element1', 1: 'path.to.element2'}, 'port2': {0: 'path.to.element3'} }

ports property

A dictionary mapping port names to their corresponding Port objects.

The keys of the dictionary are the names of the ports. The values are Port objects representing the ports.

Returns:

input_ports property

input_ports: Tuple[Port[Instance], Port[Instance]]

The input ports of the gate as a 2-tuple.

output_ports property

output_ports: Tuple[Port[Instance], ...]

Returns a tuple of output ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as outputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the output ports.

has_unconnected_port_segments property

has_unconnected_port_segments: bool

Returns True if the instance has at least one unconnected port segment.

signals property

signals: Dict[str, SignalArray]

A dictionary with all signals currently present on all ports of this instance.

is_blackbox property

is_blackbox: bool

Flag indicating whether the instance represents neither a primitive element nor a module instance.

If True, this instance does not have a module definition, and is also not a basic component (i.e. a primitive gate instance) from the internal gate library, such as a gate or flip-flop.

y_width property

y_width: PositiveInt

Width of the gate, based on a certain port's width, depending on the actual gate.

a_width property

a_width: PositiveInt

Width of the gate's A port.

b_width property

b_width: PositiveInt

Width of the gate's B port.

is_combinational property

is_combinational: bool

Whether instances of this gate are considered combinational gates.

True for combinational gates, such as AND gates or arithmetic gates. False for flip-flops and latches.

is_sequential property

is_sequential: bool

Whether instances of this gate are considered sequential gates.

False for combinational gates, such as AND gates or arithmetic gates. True for flip-flops and latches.

output_port property

output_port: Port[Instance]

The output port of the gate.

data_width property

data_width: int

The data width of this instance.

Defaults to the data width of the output port. Can be overwritten in extended classes.

In contrast to self.width, which is used for the creation and initialization, this property is linked to the data width of the output port. This property is useful when the data width of the output port can be changed.

a_signed property

a_signed: bool

The signedness of input port A.

b_signed property

b_signed: bool

The signedness of input port B.

truth_table property

truth_table: Dict[Tuple[Signal, Signal], Signal]

A simple truth table as a dictionary.

This dictionary contains the input-output mapping for unary gates that evaluate bitwise (e.g. AndGate, OrGate). Not implemented for arithmetic gates (e.g. Adder).

change_mutability

change_mutability(is_now_locked: bool, recursive: bool = False) -> Self

Change the mutability status of this instance and optionally its ports.

This method allows setting whether this instance can be modified or not. If recursive is set to True, it also applies the same mutability status to all ports of this instance.

Parameters:

  • is_now_locked

    (bool) –

    The new mutability status for this instance.

  • recursive

    (bool, default: False ) –

    Whether to apply the change recursively to its ports. Defaults to False.

evaluate

evaluate() -> None

Evaluates the gate's output signal based on its input signals.

This method is called when the gate's input signals change, and it updates the gate's output signal accordingly.

all_connections

all_connections(
    include_unconnected: bool,
) -> Dict[str, Dict[int, WireSegmentPath]]

Returns a dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port.

Parameters:

  • include_unconnected

    (bool) –

    Whether to include unconnected ports in the result.

Returns:

model_post_init

model_post_init(__context: object) -> None

Initializes the gate's ports and connections.

This method is called after the gate's attributes have been initialized, and it sets up the gate's ports and connections.

connect

connect(
    port_name: str,
    ws_path: Optional[WireSegmentPath],
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add connections to the specified port of this instance.

This method can establish multiple connections if a range of indices is provided.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection(s) should be established.

  • ws_path

    (Optional[WireSegmentPath]) –

    The path of the wire segment that will be connected to this port. If None, the associated port (segment) remains unconnected.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

Raises:

  • ObjectLockedError

    If this instance is currently locked, and no connection can be made.

disconnect

disconnect(port_name: str, index: Optional[int] = None) -> None

Remove an existing connection from a specified port of this instance.

This method disconnects the wire segment at the given index within the specified port_name.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be removed.

  • index

    (Optional[int], default: None ) –

    The bit index within the port for this disconnection. Defaults to None, which completely disconnects the port.

Raises:

get_connection

get_connection(
    port_name: str, index: Optional[NonNegativeInt] = None
) -> Union[WireSegmentPath, Dict[int, WireSegmentPath], None]

Retrieve the connection path associated with a specified port and bit index.

If index is provided, this method returns the wire segment path connected to that specific bit within the port. Otherwise, it returns all connections for the given port as a dictionary mapping indices to WireSegmentPaths.

Parameters:

  • port_name

    (str) –

    The name of the port for which to retrieve the connection(s).

  • index

    (Optional[NonNegativeInt], default: None ) –

    The bit index within the port. Defaults to None.

Returns:

modify_connection

modify_connection(
    port_name: str, ws_path: WireSegmentPath, index: NonNegativeInt = 0
) -> None

Modify an existing connection within a specified port of this instance.

This method updates the wire segment path at the given index within the specified port_name. If the index does not exist yet, it is newly added, changing the width of the port.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be modified.

  • ws_path

    (WireSegmentPath) –

    The new wire segment path for this connection.

  • index

    (NonNegativeInt, default: 0 ) –

    The bit index within the port. Defaults to 0.

connect_modify

connect_modify(
    port_name: str,
    ws_path: WireSegmentPath,
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add a new connection or modify an existing one within the specified port of this instance.

If the connection already exists at the given index and port_name, it will be modified. Otherwise, a new connection is added.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be established or updated.

  • ws_path

    (WireSegmentPath) –

    The path of the wire segment that will be connected to this port.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

tie_port

tie_port(name: str, index: NonNegativeInt, sig_value: LogicLevel) -> None

Set a constant signal value for the specified port and bit index.

If the specified port does not exist, an error message is logged and the function returns False. Otherwise, the method tries to set the constant signal value for that port and returns True if successful.

Does not work for instance output ports, as they are always driven by their parent instances.

Parameters:

  • name

    (str) –

    The name of the port.

  • index

    (NonNegativeInt) –

    The bit index within the port.

  • sig_value

    (LogicLevel) –

    The constant signal value to be set ('0', '1', or 'Z').

Raises:

  • ObjectNotFoundError

    If no such port or port segment exists.

  • AlreadyConnectedError

    (raised by: PortSegment.tie_signal) If this segment is belongs to a load port and is already connected to a wire, from which it receives its value.

  • InvalidDirectionError

    (raised by: PortSegment.tie_signal) If this port segment belongs to an instance output port, which is driven by the instance inputs and the instance's internal logic.

  • InvalidSignalError

    (raised by: PortSegment.tie_signal) If an invalid value is provided.

has_tied_ports

has_tied_ports() -> bool

Checks the ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any ports of this instance are tied to constant values. False otherwise, i.e. all ports are connected to wires.

has_tied_inputs

has_tied_inputs() -> bool

Checks the input ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any input ports of this instance are tied to constant values. False otherwise, i.e. all input ports are connected to wires.

has_tied_outputs

has_tied_outputs() -> bool

Checks the output ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any output ports of this instance are tied to constant values. False otherwise, i.e. all output ports are connected to wires.

update_signedness

update_signedness(port_name: str) -> None

Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

Parameters:

  • port_name

    (str) –

    The name of the port, of which the signedness value is retrieved.

split

split() -> Dict[NonNegativeInt, Self]

Performs a bit-wise split on this instance.

If this instance supports splitting and has a data width of n bit, this method splits this instance into n 1-bit instances. This works for instances, where each output bit depends only on the corresponding input bit(s), e.g. an AND gate or a D-Flipflop.

Returns:

  • Dict[NonNegativeInt, Self]

    Dict[int, Instance]: An n-bit large dictionary, where each key conforms to a bit of the original instance, and each value is an 1-bit instance representing the corresponding "slice" of the original instance.

Raises:

  • SplittingUnsupportedError

    If this instance does not support splitting. Happens for any gate or instance whose behavior depends on the whole bus, and splitting would make it lose its meaning.

p2v

p2v(
    port: ANY_PORT,
    exclude_indices: Optional[List[int]] = None,
    include_indices: Optional[List[int]] = None,
) -> str

Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a Port object and converts them to their corresponding Verilog signal structure (p2v -> Port to Verilog signal syntax). For each segment of the port, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port is set to a constant, the corresponding constant wire segment placeholder is used instead. Port segments can be excluded from the conversion by providing a list of indices to the exclude_indices parameter, indicating which segments should be excluded from the conversion (e.g. segments that are known to be unconnected). Vice versa, only a certain subset of the port's segments may be converted to Verilog syntax, if include_indices is a given list of port indices. All indices not present in the list will be excluded from the conversion.

Parameters:

  • port

    (Port) –

    The Port object to convert.

  • exclude_indices

    (List[int], default: None ) –

    A list of indices to exclude from the conversion. Defaults to None.

  • include_indices

    (List[int], default: None ) –

    A list of indices (i.e. port slices) to include only for the conversion. Defaults to None.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

  • ObjectNotFoundError

    If the wire connected to a certain port segment could not be found.

  • UnsupportedOperationError

    If both exclude_indices and include_indices are specified. Only one of both may be given when calling this method.

ps2v

Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a PortSegment dictionary and converts them to their corresponding Verilog signal structure (ps2v -> PortSegment to Verilog signal syntax). For each segment, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port segment is set to a constant, the corresponding constant wire segment placeholder is used instead.

Parameters:

  • ps_dict

    (Dict[int, PortSegment]) –

    The PortSegment dictionary to convert. Each key (int) conforms to the index of the associated PortSegment object.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

set

set(
    port_name: str,
    new_signal: SignalOrLogicLevel,
    idx: Union[int, List[int]] = 0,
) -> None

Sets the signal on a port.

Parameters:

  • port_name

    (str) –

    The name of the port to set the signal on.

  • new_signal

    (Signal) –

    The new signal value.

  • idx

    (Union[int, List[int]], default: 0 ) –

    The index (or indices) to apply the given signal to. Can either be an integer (single index to set) or an iterable of integers (e.g. a list of indices). For every integer of the iterable the signal value of the corresponding port index is set to the given new_signal. Defaults to 0.

Example

from netlist_carpentry.utils.gate_factory import and_gate module = Module(name='m') a = module.create_port('a', 'input', width=6) instance = and_gate(module, 'inst', A=a)

This sets the value of bit 0 of port A to HIGH

instance.set('A', 1, 0) instance.ports['A'].signal_str 'xxxxx1'

This sets the value of bits 1, 3 and 5 of port A to LOW, leaving the other bits as they already are.

instance.set('A', 0, [1, 3, 5]) instance.ports['A'].signal_str '0x0x01'

get_result_vector

get_result_vector(s1: SignalArray, s2: SignalArray) -> SignalArray

Returns the result of this gate's operation for full signal vectors.

This method provides a unified interface for all binary gates to operate on :class:SignalArray (multi-bit) inputs. The default implementation iterates over each bit index and calls :meth:get_result for bitwise gates (e.g. AndGate, OrGate, XorGate). Gates that operate on the full vectors (e.g. arithmetic gates like Adder, Subtractor, or comparison gates like LessThan) override this method with their vector-level logic.

For comparison gates that produce a single bit from two N-bit inputs (e.g. LessThan, Equal), the output is a 1-bit :class:SignalArray.

Parameters:

Returns:

  • SignalArray ( SignalArray ) –

    The result of this gate's operation on the given signals. For bitwise gates, this has the same width as the inputs. For comparison/reduction gates, this is a 1-bit SignalArray.

signals_in

signals_in(idx: NonNegativeInt = 0) -> Tuple[Signal, Signal]

The input signals of the gate.

Returns:

signal_out

signal_out(idx: NonNegativeInt = 0) -> Signal

The output signal of the gate.

Returns:

  • Signal ( Signal ) –

    The output signal of the gate.

OrGate

Bases: BinaryGate, BaseModel

An OR gate.

An OR gate is a gate that produces a HIGH output signal if either of its input signals is HIGH. Otherwise, it produces a LOW output signal.

Methods:

  • change_mutability

    Change the mutability status of this instance and optionally its ports.

  • evaluate

    Evaluates the gate's output signal based on its input signals.

  • all_connections

    Returns a dictionary mapping port names to their corresponding connection paths.

  • model_post_init

    Initializes the gate's ports and connections.

  • connect

    Add connections to the specified port of this instance.

  • disconnect

    Remove an existing connection from a specified port of this instance.

  • get_connection

    Retrieve the connection path associated with a specified port and bit index.

  • modify_connection

    Modify an existing connection within a specified port of this instance.

  • connect_modify

    Add a new connection or modify an existing one within the specified port of this instance.

  • tie_port

    Set a constant signal value for the specified port and bit index.

  • has_tied_ports

    Checks the ports of this instance whether any are tied to constant values.

  • has_tied_inputs

    Checks the input ports of this instance whether any are tied to constant values.

  • has_tied_outputs

    Checks the output ports of this instance whether any are tied to constant values.

  • update_signedness

    Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

  • split

    Performs a bit-wise split on this instance.

  • p2v

    Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

  • ps2v

    Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

  • set

    Sets the signal on a port.

  • get_result_vector

    Returns the result of this gate's operation for full signal vectors.

  • signals_in

    The input signals of the gate.

  • signal_out

    The output signal of the gate.

Attributes:

name instance-attribute

name: str

The name of the element.

!!! Do not modify this variable after instantiating it. Use NetlistElement.set_name() instead. Modifying this variable might lead to inconsistencies later on.

metadata class-attribute instance-attribute

Metadata of a netlist element.

Can be user-defined, or e. g. by Yosys (such as src for the HDL source). Is also grouped by categories, i.e. all metadata from Yosys can be accessed via Module.metadata["yosys"], or via Module.metadata.yosys, which both return a dictionary of all metadata. Read the documentation of MetaDataMixin for more information.

path property

Returns the InstancePath of the netlist element.

The InstancePath object is constructed using the element's type and its raw hierarchical path.

Returns:

  • InstancePath ( InstancePath ) –

    The hierarchical path of the netlist element.

type property

type: EType

The type of the element, which is an instance.

hierarchy_level property

hierarchy_level: int

The level of hierarchy of the element in the design.

The hierarchy level is the number of separators in the element's raw path. For example, a top-level instance has a hierarchy level of 0, while a direct submodule instance has a hierarchy level of 1.

Returns:

  • int ( int ) –

    The hierarchy level of the element.

has_parent property

has_parent: bool

Whether this object has a parent.

circuit property

circuit: 'Circuit'

The circuit object to which this netlist element belongs to.

  • For a module, returns the circuit to which the module belongs.
  • For any other netlist element, recursively returns the circuit of the parent, which ultimately leads to a module, to which the netlist element belongs.

Raises:

  • ParentNotFoundError

    If a parent cannot be resolved somewhere in the hierarchical chain.

  • ObjectNotFoundError

    If for a module no circuit is set.

has_circuit property

has_circuit: bool

Whether this netlist element has a defined circuit it belongs to.

Tries to access self.circuit and returns whether the call was successful. Can be used instead of a try-except clause around the call to NetlistElement.circuit.

locked property

locked: bool

True if this NetlistElement instance is locked (i.e. it is currently structurally unchangeable), False if it is mutable.

Can be changed via NetlistElement.change_mutability(bool).

Immutability is used to prevent accidental changes to the design.

is_placeholder_instance property

is_placeholder_instance: bool

A placeholder represents an element that does not have a specific path.

True if this NetlistElement instance represents a placeholder, False otherwise.

can_carry_signal property

can_carry_signal: bool

Whether this exact object is able to receive, pass or hold signal values.

True for ports (as they drive or receive values) and wires (as they pass the signals from driver to load ports) as well as their respective segments. False for instances and modules.

connections property

connections: Dict[str, Dict[int, WireSegmentPath]]

A dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port. Elements with no connection (i.e. the path is None) are excluded. In case these are needed, use Instance.get_connections() instead.

Example

{ 'port1': {1: WireSegmentPath('path/to/element1'), 2: WireSegmentPath('path/to/element2')}, 'port2': {1: WireSegmentPath('path/to/element3')} }

connection_str_paths property

connection_str_paths: Dict[str, Dict[int, str]]

Returns a dictionary mapping port names to their corresponding connection paths as strings.

The keys are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are the raw string paths.

Example

{ 'port1': {0: 'path.to.element1', 1: 'path.to.element2'}, 'port2': {0: 'path.to.element3'} }

ports property

A dictionary mapping port names to their corresponding Port objects.

The keys of the dictionary are the names of the ports. The values are Port objects representing the ports.

Returns:

input_ports property

input_ports: Tuple[Port[Instance], Port[Instance]]

The input ports of the gate as a 2-tuple.

output_ports property

output_ports: Tuple[Port[Instance], ...]

Returns a tuple of output ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as outputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the output ports.

has_unconnected_port_segments property

has_unconnected_port_segments: bool

Returns True if the instance has at least one unconnected port segment.

signals property

signals: Dict[str, SignalArray]

A dictionary with all signals currently present on all ports of this instance.

is_blackbox property

is_blackbox: bool

Flag indicating whether the instance represents neither a primitive element nor a module instance.

If True, this instance does not have a module definition, and is also not a basic component (i.e. a primitive gate instance) from the internal gate library, such as a gate or flip-flop.

y_width property

y_width: PositiveInt

Width of the gate, based on a certain port's width, depending on the actual gate.

a_width property

a_width: PositiveInt

Width of the gate's A port.

b_width property

b_width: PositiveInt

Width of the gate's B port.

is_combinational property

is_combinational: bool

Whether instances of this gate are considered combinational gates.

True for combinational gates, such as AND gates or arithmetic gates. False for flip-flops and latches.

is_sequential property

is_sequential: bool

Whether instances of this gate are considered sequential gates.

False for combinational gates, such as AND gates or arithmetic gates. True for flip-flops and latches.

output_port property

output_port: Port[Instance]

The output port of the gate.

data_width property

data_width: int

The data width of this instance.

Defaults to the data width of the output port. Can be overwritten in extended classes.

In contrast to self.width, which is used for the creation and initialization, this property is linked to the data width of the output port. This property is useful when the data width of the output port can be changed.

a_signed property

a_signed: bool

The signedness of input port A.

b_signed property

b_signed: bool

The signedness of input port B.

truth_table property

truth_table: Dict[Tuple[Signal, Signal], Signal]

A simple truth table as a dictionary.

This dictionary contains the input-output mapping for unary gates that evaluate bitwise (e.g. AndGate, OrGate). Not implemented for arithmetic gates (e.g. Adder).

change_mutability

change_mutability(is_now_locked: bool, recursive: bool = False) -> Self

Change the mutability status of this instance and optionally its ports.

This method allows setting whether this instance can be modified or not. If recursive is set to True, it also applies the same mutability status to all ports of this instance.

Parameters:

  • is_now_locked

    (bool) –

    The new mutability status for this instance.

  • recursive

    (bool, default: False ) –

    Whether to apply the change recursively to its ports. Defaults to False.

evaluate

evaluate() -> None

Evaluates the gate's output signal based on its input signals.

This method is called when the gate's input signals change, and it updates the gate's output signal accordingly.

all_connections

all_connections(
    include_unconnected: bool,
) -> Dict[str, Dict[int, WireSegmentPath]]

Returns a dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port.

Parameters:

  • include_unconnected

    (bool) –

    Whether to include unconnected ports in the result.

Returns:

model_post_init

model_post_init(__context: object) -> None

Initializes the gate's ports and connections.

This method is called after the gate's attributes have been initialized, and it sets up the gate's ports and connections.

connect

connect(
    port_name: str,
    ws_path: Optional[WireSegmentPath],
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add connections to the specified port of this instance.

This method can establish multiple connections if a range of indices is provided.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection(s) should be established.

  • ws_path

    (Optional[WireSegmentPath]) –

    The path of the wire segment that will be connected to this port. If None, the associated port (segment) remains unconnected.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

Raises:

  • ObjectLockedError

    If this instance is currently locked, and no connection can be made.

disconnect

disconnect(port_name: str, index: Optional[int] = None) -> None

Remove an existing connection from a specified port of this instance.

This method disconnects the wire segment at the given index within the specified port_name.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be removed.

  • index

    (Optional[int], default: None ) –

    The bit index within the port for this disconnection. Defaults to None, which completely disconnects the port.

Raises:

get_connection

get_connection(
    port_name: str, index: Optional[NonNegativeInt] = None
) -> Union[WireSegmentPath, Dict[int, WireSegmentPath], None]

Retrieve the connection path associated with a specified port and bit index.

If index is provided, this method returns the wire segment path connected to that specific bit within the port. Otherwise, it returns all connections for the given port as a dictionary mapping indices to WireSegmentPaths.

Parameters:

  • port_name

    (str) –

    The name of the port for which to retrieve the connection(s).

  • index

    (Optional[NonNegativeInt], default: None ) –

    The bit index within the port. Defaults to None.

Returns:

modify_connection

modify_connection(
    port_name: str, ws_path: WireSegmentPath, index: NonNegativeInt = 0
) -> None

Modify an existing connection within a specified port of this instance.

This method updates the wire segment path at the given index within the specified port_name. If the index does not exist yet, it is newly added, changing the width of the port.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be modified.

  • ws_path

    (WireSegmentPath) –

    The new wire segment path for this connection.

  • index

    (NonNegativeInt, default: 0 ) –

    The bit index within the port. Defaults to 0.

connect_modify

connect_modify(
    port_name: str,
    ws_path: WireSegmentPath,
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add a new connection or modify an existing one within the specified port of this instance.

If the connection already exists at the given index and port_name, it will be modified. Otherwise, a new connection is added.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be established or updated.

  • ws_path

    (WireSegmentPath) –

    The path of the wire segment that will be connected to this port.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

tie_port

tie_port(name: str, index: NonNegativeInt, sig_value: LogicLevel) -> None

Set a constant signal value for the specified port and bit index.

If the specified port does not exist, an error message is logged and the function returns False. Otherwise, the method tries to set the constant signal value for that port and returns True if successful.

Does not work for instance output ports, as they are always driven by their parent instances.

Parameters:

  • name

    (str) –

    The name of the port.

  • index

    (NonNegativeInt) –

    The bit index within the port.

  • sig_value

    (LogicLevel) –

    The constant signal value to be set ('0', '1', or 'Z').

Raises:

  • ObjectNotFoundError

    If no such port or port segment exists.

  • AlreadyConnectedError

    (raised by: PortSegment.tie_signal) If this segment is belongs to a load port and is already connected to a wire, from which it receives its value.

  • InvalidDirectionError

    (raised by: PortSegment.tie_signal) If this port segment belongs to an instance output port, which is driven by the instance inputs and the instance's internal logic.

  • InvalidSignalError

    (raised by: PortSegment.tie_signal) If an invalid value is provided.

has_tied_ports

has_tied_ports() -> bool

Checks the ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any ports of this instance are tied to constant values. False otherwise, i.e. all ports are connected to wires.

has_tied_inputs

has_tied_inputs() -> bool

Checks the input ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any input ports of this instance are tied to constant values. False otherwise, i.e. all input ports are connected to wires.

has_tied_outputs

has_tied_outputs() -> bool

Checks the output ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any output ports of this instance are tied to constant values. False otherwise, i.e. all output ports are connected to wires.

update_signedness

update_signedness(port_name: str) -> None

Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

Parameters:

  • port_name

    (str) –

    The name of the port, of which the signedness value is retrieved.

split

split() -> Dict[NonNegativeInt, Self]

Performs a bit-wise split on this instance.

If this instance supports splitting and has a data width of n bit, this method splits this instance into n 1-bit instances. This works for instances, where each output bit depends only on the corresponding input bit(s), e.g. an AND gate or a D-Flipflop.

Returns:

  • Dict[NonNegativeInt, Self]

    Dict[int, Instance]: An n-bit large dictionary, where each key conforms to a bit of the original instance, and each value is an 1-bit instance representing the corresponding "slice" of the original instance.

Raises:

  • SplittingUnsupportedError

    If this instance does not support splitting. Happens for any gate or instance whose behavior depends on the whole bus, and splitting would make it lose its meaning.

p2v

p2v(
    port: ANY_PORT,
    exclude_indices: Optional[List[int]] = None,
    include_indices: Optional[List[int]] = None,
) -> str

Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a Port object and converts them to their corresponding Verilog signal structure (p2v -> Port to Verilog signal syntax). For each segment of the port, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port is set to a constant, the corresponding constant wire segment placeholder is used instead. Port segments can be excluded from the conversion by providing a list of indices to the exclude_indices parameter, indicating which segments should be excluded from the conversion (e.g. segments that are known to be unconnected). Vice versa, only a certain subset of the port's segments may be converted to Verilog syntax, if include_indices is a given list of port indices. All indices not present in the list will be excluded from the conversion.

Parameters:

  • port

    (Port) –

    The Port object to convert.

  • exclude_indices

    (List[int], default: None ) –

    A list of indices to exclude from the conversion. Defaults to None.

  • include_indices

    (List[int], default: None ) –

    A list of indices (i.e. port slices) to include only for the conversion. Defaults to None.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

  • ObjectNotFoundError

    If the wire connected to a certain port segment could not be found.

  • UnsupportedOperationError

    If both exclude_indices and include_indices are specified. Only one of both may be given when calling this method.

ps2v

Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a PortSegment dictionary and converts them to their corresponding Verilog signal structure (ps2v -> PortSegment to Verilog signal syntax). For each segment, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port segment is set to a constant, the corresponding constant wire segment placeholder is used instead.

Parameters:

  • ps_dict

    (Dict[int, PortSegment]) –

    The PortSegment dictionary to convert. Each key (int) conforms to the index of the associated PortSegment object.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

set

set(
    port_name: str,
    new_signal: SignalOrLogicLevel,
    idx: Union[int, List[int]] = 0,
) -> None

Sets the signal on a port.

Parameters:

  • port_name

    (str) –

    The name of the port to set the signal on.

  • new_signal

    (Signal) –

    The new signal value.

  • idx

    (Union[int, List[int]], default: 0 ) –

    The index (or indices) to apply the given signal to. Can either be an integer (single index to set) or an iterable of integers (e.g. a list of indices). For every integer of the iterable the signal value of the corresponding port index is set to the given new_signal. Defaults to 0.

Example

from netlist_carpentry.utils.gate_factory import and_gate module = Module(name='m') a = module.create_port('a', 'input', width=6) instance = and_gate(module, 'inst', A=a)

This sets the value of bit 0 of port A to HIGH

instance.set('A', 1, 0) instance.ports['A'].signal_str 'xxxxx1'

This sets the value of bits 1, 3 and 5 of port A to LOW, leaving the other bits as they already are.

instance.set('A', 0, [1, 3, 5]) instance.ports['A'].signal_str '0x0x01'

get_result_vector

get_result_vector(s1: SignalArray, s2: SignalArray) -> SignalArray

Returns the result of this gate's operation for full signal vectors.

This method provides a unified interface for all binary gates to operate on :class:SignalArray (multi-bit) inputs. The default implementation iterates over each bit index and calls :meth:get_result for bitwise gates (e.g. AndGate, OrGate, XorGate). Gates that operate on the full vectors (e.g. arithmetic gates like Adder, Subtractor, or comparison gates like LessThan) override this method with their vector-level logic.

For comparison gates that produce a single bit from two N-bit inputs (e.g. LessThan, Equal), the output is a 1-bit :class:SignalArray.

Parameters:

Returns:

  • SignalArray ( SignalArray ) –

    The result of this gate's operation on the given signals. For bitwise gates, this has the same width as the inputs. For comparison/reduction gates, this is a 1-bit SignalArray.

signals_in

signals_in(idx: NonNegativeInt = 0) -> Tuple[Signal, Signal]

The input signals of the gate.

Returns:

signal_out

signal_out(idx: NonNegativeInt = 0) -> Signal

The output signal of the gate.

Returns:

  • Signal ( Signal ) –

    The output signal of the gate.

XorGate

Bases: BinaryGate, BaseModel

An XOR gate.

An XOR gate is a gate that produces a HIGH output signal if its input signals are different. Otherwise, it produces a LOW output signal.

Methods:

  • change_mutability

    Change the mutability status of this instance and optionally its ports.

  • evaluate

    Evaluates the gate's output signal based on its input signals.

  • all_connections

    Returns a dictionary mapping port names to their corresponding connection paths.

  • model_post_init

    Initializes the gate's ports and connections.

  • connect

    Add connections to the specified port of this instance.

  • disconnect

    Remove an existing connection from a specified port of this instance.

  • get_connection

    Retrieve the connection path associated with a specified port and bit index.

  • modify_connection

    Modify an existing connection within a specified port of this instance.

  • connect_modify

    Add a new connection or modify an existing one within the specified port of this instance.

  • tie_port

    Set a constant signal value for the specified port and bit index.

  • has_tied_ports

    Checks the ports of this instance whether any are tied to constant values.

  • has_tied_inputs

    Checks the input ports of this instance whether any are tied to constant values.

  • has_tied_outputs

    Checks the output ports of this instance whether any are tied to constant values.

  • update_signedness

    Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

  • split

    Performs a bit-wise split on this instance.

  • p2v

    Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

  • ps2v

    Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

  • set

    Sets the signal on a port.

  • get_result_vector

    Returns the result of this gate's operation for full signal vectors.

  • signals_in

    The input signals of the gate.

  • signal_out

    The output signal of the gate.

Attributes:

name instance-attribute

name: str

The name of the element.

!!! Do not modify this variable after instantiating it. Use NetlistElement.set_name() instead. Modifying this variable might lead to inconsistencies later on.

metadata class-attribute instance-attribute

Metadata of a netlist element.

Can be user-defined, or e. g. by Yosys (such as src for the HDL source). Is also grouped by categories, i.e. all metadata from Yosys can be accessed via Module.metadata["yosys"], or via Module.metadata.yosys, which both return a dictionary of all metadata. Read the documentation of MetaDataMixin for more information.

path property

Returns the InstancePath of the netlist element.

The InstancePath object is constructed using the element's type and its raw hierarchical path.

Returns:

  • InstancePath ( InstancePath ) –

    The hierarchical path of the netlist element.

type property

type: EType

The type of the element, which is an instance.

hierarchy_level property

hierarchy_level: int

The level of hierarchy of the element in the design.

The hierarchy level is the number of separators in the element's raw path. For example, a top-level instance has a hierarchy level of 0, while a direct submodule instance has a hierarchy level of 1.

Returns:

  • int ( int ) –

    The hierarchy level of the element.

has_parent property

has_parent: bool

Whether this object has a parent.

circuit property

circuit: 'Circuit'

The circuit object to which this netlist element belongs to.

  • For a module, returns the circuit to which the module belongs.
  • For any other netlist element, recursively returns the circuit of the parent, which ultimately leads to a module, to which the netlist element belongs.

Raises:

  • ParentNotFoundError

    If a parent cannot be resolved somewhere in the hierarchical chain.

  • ObjectNotFoundError

    If for a module no circuit is set.

has_circuit property

has_circuit: bool

Whether this netlist element has a defined circuit it belongs to.

Tries to access self.circuit and returns whether the call was successful. Can be used instead of a try-except clause around the call to NetlistElement.circuit.

locked property

locked: bool

True if this NetlistElement instance is locked (i.e. it is currently structurally unchangeable), False if it is mutable.

Can be changed via NetlistElement.change_mutability(bool).

Immutability is used to prevent accidental changes to the design.

is_placeholder_instance property

is_placeholder_instance: bool

A placeholder represents an element that does not have a specific path.

True if this NetlistElement instance represents a placeholder, False otherwise.

can_carry_signal property

can_carry_signal: bool

Whether this exact object is able to receive, pass or hold signal values.

True for ports (as they drive or receive values) and wires (as they pass the signals from driver to load ports) as well as their respective segments. False for instances and modules.

connections property

connections: Dict[str, Dict[int, WireSegmentPath]]

A dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port. Elements with no connection (i.e. the path is None) are excluded. In case these are needed, use Instance.get_connections() instead.

Example

{ 'port1': {1: WireSegmentPath('path/to/element1'), 2: WireSegmentPath('path/to/element2')}, 'port2': {1: WireSegmentPath('path/to/element3')} }

connection_str_paths property

connection_str_paths: Dict[str, Dict[int, str]]

Returns a dictionary mapping port names to their corresponding connection paths as strings.

The keys are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are the raw string paths.

Example

{ 'port1': {0: 'path.to.element1', 1: 'path.to.element2'}, 'port2': {0: 'path.to.element3'} }

ports property

A dictionary mapping port names to their corresponding Port objects.

The keys of the dictionary are the names of the ports. The values are Port objects representing the ports.

Returns:

input_ports property

input_ports: Tuple[Port[Instance], Port[Instance]]

The input ports of the gate as a 2-tuple.

output_ports property

output_ports: Tuple[Port[Instance], ...]

Returns a tuple of output ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as outputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the output ports.

has_unconnected_port_segments property

has_unconnected_port_segments: bool

Returns True if the instance has at least one unconnected port segment.

signals property

signals: Dict[str, SignalArray]

A dictionary with all signals currently present on all ports of this instance.

is_blackbox property

is_blackbox: bool

Flag indicating whether the instance represents neither a primitive element nor a module instance.

If True, this instance does not have a module definition, and is also not a basic component (i.e. a primitive gate instance) from the internal gate library, such as a gate or flip-flop.

y_width property

y_width: PositiveInt

Width of the gate, based on a certain port's width, depending on the actual gate.

a_width property

a_width: PositiveInt

Width of the gate's A port.

b_width property

b_width: PositiveInt

Width of the gate's B port.

is_combinational property

is_combinational: bool

Whether instances of this gate are considered combinational gates.

True for combinational gates, such as AND gates or arithmetic gates. False for flip-flops and latches.

is_sequential property

is_sequential: bool

Whether instances of this gate are considered sequential gates.

False for combinational gates, such as AND gates or arithmetic gates. True for flip-flops and latches.

output_port property

output_port: Port[Instance]

The output port of the gate.

data_width property

data_width: int

The data width of this instance.

Defaults to the data width of the output port. Can be overwritten in extended classes.

In contrast to self.width, which is used for the creation and initialization, this property is linked to the data width of the output port. This property is useful when the data width of the output port can be changed.

a_signed property

a_signed: bool

The signedness of input port A.

b_signed property

b_signed: bool

The signedness of input port B.

truth_table property

truth_table: Dict[Tuple[Signal, Signal], Signal]

A simple truth table as a dictionary.

This dictionary contains the input-output mapping for unary gates that evaluate bitwise (e.g. AndGate, OrGate). Not implemented for arithmetic gates (e.g. Adder).

change_mutability

change_mutability(is_now_locked: bool, recursive: bool = False) -> Self

Change the mutability status of this instance and optionally its ports.

This method allows setting whether this instance can be modified or not. If recursive is set to True, it also applies the same mutability status to all ports of this instance.

Parameters:

  • is_now_locked

    (bool) –

    The new mutability status for this instance.

  • recursive

    (bool, default: False ) –

    Whether to apply the change recursively to its ports. Defaults to False.

evaluate

evaluate() -> None

Evaluates the gate's output signal based on its input signals.

This method is called when the gate's input signals change, and it updates the gate's output signal accordingly.

all_connections

all_connections(
    include_unconnected: bool,
) -> Dict[str, Dict[int, WireSegmentPath]]

Returns a dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port.

Parameters:

  • include_unconnected

    (bool) –

    Whether to include unconnected ports in the result.

Returns:

model_post_init

model_post_init(__context: object) -> None

Initializes the gate's ports and connections.

This method is called after the gate's attributes have been initialized, and it sets up the gate's ports and connections.

connect

connect(
    port_name: str,
    ws_path: Optional[WireSegmentPath],
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add connections to the specified port of this instance.

This method can establish multiple connections if a range of indices is provided.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection(s) should be established.

  • ws_path

    (Optional[WireSegmentPath]) –

    The path of the wire segment that will be connected to this port. If None, the associated port (segment) remains unconnected.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

Raises:

  • ObjectLockedError

    If this instance is currently locked, and no connection can be made.

disconnect

disconnect(port_name: str, index: Optional[int] = None) -> None

Remove an existing connection from a specified port of this instance.

This method disconnects the wire segment at the given index within the specified port_name.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be removed.

  • index

    (Optional[int], default: None ) –

    The bit index within the port for this disconnection. Defaults to None, which completely disconnects the port.

Raises:

get_connection

get_connection(
    port_name: str, index: Optional[NonNegativeInt] = None
) -> Union[WireSegmentPath, Dict[int, WireSegmentPath], None]

Retrieve the connection path associated with a specified port and bit index.

If index is provided, this method returns the wire segment path connected to that specific bit within the port. Otherwise, it returns all connections for the given port as a dictionary mapping indices to WireSegmentPaths.

Parameters:

  • port_name

    (str) –

    The name of the port for which to retrieve the connection(s).

  • index

    (Optional[NonNegativeInt], default: None ) –

    The bit index within the port. Defaults to None.

Returns:

modify_connection

modify_connection(
    port_name: str, ws_path: WireSegmentPath, index: NonNegativeInt = 0
) -> None

Modify an existing connection within a specified port of this instance.

This method updates the wire segment path at the given index within the specified port_name. If the index does not exist yet, it is newly added, changing the width of the port.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be modified.

  • ws_path

    (WireSegmentPath) –

    The new wire segment path for this connection.

  • index

    (NonNegativeInt, default: 0 ) –

    The bit index within the port. Defaults to 0.

connect_modify

connect_modify(
    port_name: str,
    ws_path: WireSegmentPath,
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add a new connection or modify an existing one within the specified port of this instance.

If the connection already exists at the given index and port_name, it will be modified. Otherwise, a new connection is added.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be established or updated.

  • ws_path

    (WireSegmentPath) –

    The path of the wire segment that will be connected to this port.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

tie_port

tie_port(name: str, index: NonNegativeInt, sig_value: LogicLevel) -> None

Set a constant signal value for the specified port and bit index.

If the specified port does not exist, an error message is logged and the function returns False. Otherwise, the method tries to set the constant signal value for that port and returns True if successful.

Does not work for instance output ports, as they are always driven by their parent instances.

Parameters:

  • name

    (str) –

    The name of the port.

  • index

    (NonNegativeInt) –

    The bit index within the port.

  • sig_value

    (LogicLevel) –

    The constant signal value to be set ('0', '1', or 'Z').

Raises:

  • ObjectNotFoundError

    If no such port or port segment exists.

  • AlreadyConnectedError

    (raised by: PortSegment.tie_signal) If this segment is belongs to a load port and is already connected to a wire, from which it receives its value.

  • InvalidDirectionError

    (raised by: PortSegment.tie_signal) If this port segment belongs to an instance output port, which is driven by the instance inputs and the instance's internal logic.

  • InvalidSignalError

    (raised by: PortSegment.tie_signal) If an invalid value is provided.

has_tied_ports

has_tied_ports() -> bool

Checks the ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any ports of this instance are tied to constant values. False otherwise, i.e. all ports are connected to wires.

has_tied_inputs

has_tied_inputs() -> bool

Checks the input ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any input ports of this instance are tied to constant values. False otherwise, i.e. all input ports are connected to wires.

has_tied_outputs

has_tied_outputs() -> bool

Checks the output ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any output ports of this instance are tied to constant values. False otherwise, i.e. all output ports are connected to wires.

update_signedness

update_signedness(port_name: str) -> None

Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

Parameters:

  • port_name

    (str) –

    The name of the port, of which the signedness value is retrieved.

split

split() -> Dict[NonNegativeInt, Self]

Performs a bit-wise split on this instance.

If this instance supports splitting and has a data width of n bit, this method splits this instance into n 1-bit instances. This works for instances, where each output bit depends only on the corresponding input bit(s), e.g. an AND gate or a D-Flipflop.

Returns:

  • Dict[NonNegativeInt, Self]

    Dict[int, Instance]: An n-bit large dictionary, where each key conforms to a bit of the original instance, and each value is an 1-bit instance representing the corresponding "slice" of the original instance.

Raises:

  • SplittingUnsupportedError

    If this instance does not support splitting. Happens for any gate or instance whose behavior depends on the whole bus, and splitting would make it lose its meaning.

p2v

p2v(
    port: ANY_PORT,
    exclude_indices: Optional[List[int]] = None,
    include_indices: Optional[List[int]] = None,
) -> str

Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a Port object and converts them to their corresponding Verilog signal structure (p2v -> Port to Verilog signal syntax). For each segment of the port, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port is set to a constant, the corresponding constant wire segment placeholder is used instead. Port segments can be excluded from the conversion by providing a list of indices to the exclude_indices parameter, indicating which segments should be excluded from the conversion (e.g. segments that are known to be unconnected). Vice versa, only a certain subset of the port's segments may be converted to Verilog syntax, if include_indices is a given list of port indices. All indices not present in the list will be excluded from the conversion.

Parameters:

  • port

    (Port) –

    The Port object to convert.

  • exclude_indices

    (List[int], default: None ) –

    A list of indices to exclude from the conversion. Defaults to None.

  • include_indices

    (List[int], default: None ) –

    A list of indices (i.e. port slices) to include only for the conversion. Defaults to None.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

  • ObjectNotFoundError

    If the wire connected to a certain port segment could not be found.

  • UnsupportedOperationError

    If both exclude_indices and include_indices are specified. Only one of both may be given when calling this method.

ps2v

Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a PortSegment dictionary and converts them to their corresponding Verilog signal structure (ps2v -> PortSegment to Verilog signal syntax). For each segment, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port segment is set to a constant, the corresponding constant wire segment placeholder is used instead.

Parameters:

  • ps_dict

    (Dict[int, PortSegment]) –

    The PortSegment dictionary to convert. Each key (int) conforms to the index of the associated PortSegment object.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

set

set(
    port_name: str,
    new_signal: SignalOrLogicLevel,
    idx: Union[int, List[int]] = 0,
) -> None

Sets the signal on a port.

Parameters:

  • port_name

    (str) –

    The name of the port to set the signal on.

  • new_signal

    (Signal) –

    The new signal value.

  • idx

    (Union[int, List[int]], default: 0 ) –

    The index (or indices) to apply the given signal to. Can either be an integer (single index to set) or an iterable of integers (e.g. a list of indices). For every integer of the iterable the signal value of the corresponding port index is set to the given new_signal. Defaults to 0.

Example

from netlist_carpentry.utils.gate_factory import and_gate module = Module(name='m') a = module.create_port('a', 'input', width=6) instance = and_gate(module, 'inst', A=a)

This sets the value of bit 0 of port A to HIGH

instance.set('A', 1, 0) instance.ports['A'].signal_str 'xxxxx1'

This sets the value of bits 1, 3 and 5 of port A to LOW, leaving the other bits as they already are.

instance.set('A', 0, [1, 3, 5]) instance.ports['A'].signal_str '0x0x01'

get_result_vector

get_result_vector(s1: SignalArray, s2: SignalArray) -> SignalArray

Returns the result of this gate's operation for full signal vectors.

This method provides a unified interface for all binary gates to operate on :class:SignalArray (multi-bit) inputs. The default implementation iterates over each bit index and calls :meth:get_result for bitwise gates (e.g. AndGate, OrGate, XorGate). Gates that operate on the full vectors (e.g. arithmetic gates like Adder, Subtractor, or comparison gates like LessThan) override this method with their vector-level logic.

For comparison gates that produce a single bit from two N-bit inputs (e.g. LessThan, Equal), the output is a 1-bit :class:SignalArray.

Parameters:

Returns:

  • SignalArray ( SignalArray ) –

    The result of this gate's operation on the given signals. For bitwise gates, this has the same width as the inputs. For comparison/reduction gates, this is a 1-bit SignalArray.

signals_in

signals_in(idx: NonNegativeInt = 0) -> Tuple[Signal, Signal]

The input signals of the gate.

Returns:

signal_out

signal_out(idx: NonNegativeInt = 0) -> Signal

The output signal of the gate.

Returns:

  • Signal ( Signal ) –

    The output signal of the gate.

XnorGate

Bases: BinaryGate, BaseModel

An XNOR gate.

An XNOR gate is a gate that produces a HIGH output signal if its input signals are the same. Otherwise, it produces a LOW output signal.

Methods:

  • change_mutability

    Change the mutability status of this instance and optionally its ports.

  • evaluate

    Evaluates the gate's output signal based on its input signals.

  • all_connections

    Returns a dictionary mapping port names to their corresponding connection paths.

  • model_post_init

    Initializes the gate's ports and connections.

  • connect

    Add connections to the specified port of this instance.

  • disconnect

    Remove an existing connection from a specified port of this instance.

  • get_connection

    Retrieve the connection path associated with a specified port and bit index.

  • modify_connection

    Modify an existing connection within a specified port of this instance.

  • connect_modify

    Add a new connection or modify an existing one within the specified port of this instance.

  • tie_port

    Set a constant signal value for the specified port and bit index.

  • has_tied_ports

    Checks the ports of this instance whether any are tied to constant values.

  • has_tied_inputs

    Checks the input ports of this instance whether any are tied to constant values.

  • has_tied_outputs

    Checks the output ports of this instance whether any are tied to constant values.

  • update_signedness

    Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

  • split

    Performs a bit-wise split on this instance.

  • p2v

    Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

  • ps2v

    Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

  • set

    Sets the signal on a port.

  • get_result_vector

    Returns the result of this gate's operation for full signal vectors.

  • signals_in

    The input signals of the gate.

  • signal_out

    The output signal of the gate.

Attributes:

name instance-attribute

name: str

The name of the element.

!!! Do not modify this variable after instantiating it. Use NetlistElement.set_name() instead. Modifying this variable might lead to inconsistencies later on.

metadata class-attribute instance-attribute

Metadata of a netlist element.

Can be user-defined, or e. g. by Yosys (such as src for the HDL source). Is also grouped by categories, i.e. all metadata from Yosys can be accessed via Module.metadata["yosys"], or via Module.metadata.yosys, which both return a dictionary of all metadata. Read the documentation of MetaDataMixin for more information.

path property

Returns the InstancePath of the netlist element.

The InstancePath object is constructed using the element's type and its raw hierarchical path.

Returns:

  • InstancePath ( InstancePath ) –

    The hierarchical path of the netlist element.

type property

type: EType

The type of the element, which is an instance.

hierarchy_level property

hierarchy_level: int

The level of hierarchy of the element in the design.

The hierarchy level is the number of separators in the element's raw path. For example, a top-level instance has a hierarchy level of 0, while a direct submodule instance has a hierarchy level of 1.

Returns:

  • int ( int ) –

    The hierarchy level of the element.

has_parent property

has_parent: bool

Whether this object has a parent.

circuit property

circuit: 'Circuit'

The circuit object to which this netlist element belongs to.

  • For a module, returns the circuit to which the module belongs.
  • For any other netlist element, recursively returns the circuit of the parent, which ultimately leads to a module, to which the netlist element belongs.

Raises:

  • ParentNotFoundError

    If a parent cannot be resolved somewhere in the hierarchical chain.

  • ObjectNotFoundError

    If for a module no circuit is set.

has_circuit property

has_circuit: bool

Whether this netlist element has a defined circuit it belongs to.

Tries to access self.circuit and returns whether the call was successful. Can be used instead of a try-except clause around the call to NetlistElement.circuit.

locked property

locked: bool

True if this NetlistElement instance is locked (i.e. it is currently structurally unchangeable), False if it is mutable.

Can be changed via NetlistElement.change_mutability(bool).

Immutability is used to prevent accidental changes to the design.

is_placeholder_instance property

is_placeholder_instance: bool

A placeholder represents an element that does not have a specific path.

True if this NetlistElement instance represents a placeholder, False otherwise.

can_carry_signal property

can_carry_signal: bool

Whether this exact object is able to receive, pass or hold signal values.

True for ports (as they drive or receive values) and wires (as they pass the signals from driver to load ports) as well as their respective segments. False for instances and modules.

connections property

connections: Dict[str, Dict[int, WireSegmentPath]]

A dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port. Elements with no connection (i.e. the path is None) are excluded. In case these are needed, use Instance.get_connections() instead.

Example

{ 'port1': {1: WireSegmentPath('path/to/element1'), 2: WireSegmentPath('path/to/element2')}, 'port2': {1: WireSegmentPath('path/to/element3')} }

connection_str_paths property

connection_str_paths: Dict[str, Dict[int, str]]

Returns a dictionary mapping port names to their corresponding connection paths as strings.

The keys are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are the raw string paths.

Example

{ 'port1': {0: 'path.to.element1', 1: 'path.to.element2'}, 'port2': {0: 'path.to.element3'} }

ports property

A dictionary mapping port names to their corresponding Port objects.

The keys of the dictionary are the names of the ports. The values are Port objects representing the ports.

Returns:

input_ports property

input_ports: Tuple[Port[Instance], Port[Instance]]

The input ports of the gate as a 2-tuple.

output_ports property

output_ports: Tuple[Port[Instance], ...]

Returns a tuple of output ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as outputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the output ports.

has_unconnected_port_segments property

has_unconnected_port_segments: bool

Returns True if the instance has at least one unconnected port segment.

signals property

signals: Dict[str, SignalArray]

A dictionary with all signals currently present on all ports of this instance.

is_blackbox property

is_blackbox: bool

Flag indicating whether the instance represents neither a primitive element nor a module instance.

If True, this instance does not have a module definition, and is also not a basic component (i.e. a primitive gate instance) from the internal gate library, such as a gate or flip-flop.

y_width property

y_width: PositiveInt

Width of the gate, based on a certain port's width, depending on the actual gate.

a_width property

a_width: PositiveInt

Width of the gate's A port.

b_width property

b_width: PositiveInt

Width of the gate's B port.

is_combinational property

is_combinational: bool

Whether instances of this gate are considered combinational gates.

True for combinational gates, such as AND gates or arithmetic gates. False for flip-flops and latches.

is_sequential property

is_sequential: bool

Whether instances of this gate are considered sequential gates.

False for combinational gates, such as AND gates or arithmetic gates. True for flip-flops and latches.

output_port property

output_port: Port[Instance]

The output port of the gate.

data_width property

data_width: int

The data width of this instance.

Defaults to the data width of the output port. Can be overwritten in extended classes.

In contrast to self.width, which is used for the creation and initialization, this property is linked to the data width of the output port. This property is useful when the data width of the output port can be changed.

a_signed property

a_signed: bool

The signedness of input port A.

b_signed property

b_signed: bool

The signedness of input port B.

truth_table property

truth_table: Dict[Tuple[Signal, Signal], Signal]

A simple truth table as a dictionary.

This dictionary contains the input-output mapping for unary gates that evaluate bitwise (e.g. AndGate, OrGate). Not implemented for arithmetic gates (e.g. Adder).

change_mutability

change_mutability(is_now_locked: bool, recursive: bool = False) -> Self

Change the mutability status of this instance and optionally its ports.

This method allows setting whether this instance can be modified or not. If recursive is set to True, it also applies the same mutability status to all ports of this instance.

Parameters:

  • is_now_locked

    (bool) –

    The new mutability status for this instance.

  • recursive

    (bool, default: False ) –

    Whether to apply the change recursively to its ports. Defaults to False.

evaluate

evaluate() -> None

Evaluates the gate's output signal based on its input signals.

This method is called when the gate's input signals change, and it updates the gate's output signal accordingly.

all_connections

all_connections(
    include_unconnected: bool,
) -> Dict[str, Dict[int, WireSegmentPath]]

Returns a dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port.

Parameters:

  • include_unconnected

    (bool) –

    Whether to include unconnected ports in the result.

Returns:

model_post_init

model_post_init(__context: object) -> None

Initializes the gate's ports and connections.

This method is called after the gate's attributes have been initialized, and it sets up the gate's ports and connections.

connect

connect(
    port_name: str,
    ws_path: Optional[WireSegmentPath],
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add connections to the specified port of this instance.

This method can establish multiple connections if a range of indices is provided.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection(s) should be established.

  • ws_path

    (Optional[WireSegmentPath]) –

    The path of the wire segment that will be connected to this port. If None, the associated port (segment) remains unconnected.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

Raises:

  • ObjectLockedError

    If this instance is currently locked, and no connection can be made.

disconnect

disconnect(port_name: str, index: Optional[int] = None) -> None

Remove an existing connection from a specified port of this instance.

This method disconnects the wire segment at the given index within the specified port_name.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be removed.

  • index

    (Optional[int], default: None ) –

    The bit index within the port for this disconnection. Defaults to None, which completely disconnects the port.

Raises:

get_connection

get_connection(
    port_name: str, index: Optional[NonNegativeInt] = None
) -> Union[WireSegmentPath, Dict[int, WireSegmentPath], None]

Retrieve the connection path associated with a specified port and bit index.

If index is provided, this method returns the wire segment path connected to that specific bit within the port. Otherwise, it returns all connections for the given port as a dictionary mapping indices to WireSegmentPaths.

Parameters:

  • port_name

    (str) –

    The name of the port for which to retrieve the connection(s).

  • index

    (Optional[NonNegativeInt], default: None ) –

    The bit index within the port. Defaults to None.

Returns:

modify_connection

modify_connection(
    port_name: str, ws_path: WireSegmentPath, index: NonNegativeInt = 0
) -> None

Modify an existing connection within a specified port of this instance.

This method updates the wire segment path at the given index within the specified port_name. If the index does not exist yet, it is newly added, changing the width of the port.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be modified.

  • ws_path

    (WireSegmentPath) –

    The new wire segment path for this connection.

  • index

    (NonNegativeInt, default: 0 ) –

    The bit index within the port. Defaults to 0.

connect_modify

connect_modify(
    port_name: str,
    ws_path: WireSegmentPath,
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add a new connection or modify an existing one within the specified port of this instance.

If the connection already exists at the given index and port_name, it will be modified. Otherwise, a new connection is added.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be established or updated.

  • ws_path

    (WireSegmentPath) –

    The path of the wire segment that will be connected to this port.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

tie_port

tie_port(name: str, index: NonNegativeInt, sig_value: LogicLevel) -> None

Set a constant signal value for the specified port and bit index.

If the specified port does not exist, an error message is logged and the function returns False. Otherwise, the method tries to set the constant signal value for that port and returns True if successful.

Does not work for instance output ports, as they are always driven by their parent instances.

Parameters:

  • name

    (str) –

    The name of the port.

  • index

    (NonNegativeInt) –

    The bit index within the port.

  • sig_value

    (LogicLevel) –

    The constant signal value to be set ('0', '1', or 'Z').

Raises:

  • ObjectNotFoundError

    If no such port or port segment exists.

  • AlreadyConnectedError

    (raised by: PortSegment.tie_signal) If this segment is belongs to a load port and is already connected to a wire, from which it receives its value.

  • InvalidDirectionError

    (raised by: PortSegment.tie_signal) If this port segment belongs to an instance output port, which is driven by the instance inputs and the instance's internal logic.

  • InvalidSignalError

    (raised by: PortSegment.tie_signal) If an invalid value is provided.

has_tied_ports

has_tied_ports() -> bool

Checks the ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any ports of this instance are tied to constant values. False otherwise, i.e. all ports are connected to wires.

has_tied_inputs

has_tied_inputs() -> bool

Checks the input ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any input ports of this instance are tied to constant values. False otherwise, i.e. all input ports are connected to wires.

has_tied_outputs

has_tied_outputs() -> bool

Checks the output ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any output ports of this instance are tied to constant values. False otherwise, i.e. all output ports are connected to wires.

update_signedness

update_signedness(port_name: str) -> None

Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

Parameters:

  • port_name

    (str) –

    The name of the port, of which the signedness value is retrieved.

split

split() -> Dict[NonNegativeInt, Self]

Performs a bit-wise split on this instance.

If this instance supports splitting and has a data width of n bit, this method splits this instance into n 1-bit instances. This works for instances, where each output bit depends only on the corresponding input bit(s), e.g. an AND gate or a D-Flipflop.

Returns:

  • Dict[NonNegativeInt, Self]

    Dict[int, Instance]: An n-bit large dictionary, where each key conforms to a bit of the original instance, and each value is an 1-bit instance representing the corresponding "slice" of the original instance.

Raises:

  • SplittingUnsupportedError

    If this instance does not support splitting. Happens for any gate or instance whose behavior depends on the whole bus, and splitting would make it lose its meaning.

p2v

p2v(
    port: ANY_PORT,
    exclude_indices: Optional[List[int]] = None,
    include_indices: Optional[List[int]] = None,
) -> str

Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a Port object and converts them to their corresponding Verilog signal structure (p2v -> Port to Verilog signal syntax). For each segment of the port, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port is set to a constant, the corresponding constant wire segment placeholder is used instead. Port segments can be excluded from the conversion by providing a list of indices to the exclude_indices parameter, indicating which segments should be excluded from the conversion (e.g. segments that are known to be unconnected). Vice versa, only a certain subset of the port's segments may be converted to Verilog syntax, if include_indices is a given list of port indices. All indices not present in the list will be excluded from the conversion.

Parameters:

  • port

    (Port) –

    The Port object to convert.

  • exclude_indices

    (List[int], default: None ) –

    A list of indices to exclude from the conversion. Defaults to None.

  • include_indices

    (List[int], default: None ) –

    A list of indices (i.e. port slices) to include only for the conversion. Defaults to None.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

  • ObjectNotFoundError

    If the wire connected to a certain port segment could not be found.

  • UnsupportedOperationError

    If both exclude_indices and include_indices are specified. Only one of both may be given when calling this method.

ps2v

Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a PortSegment dictionary and converts them to their corresponding Verilog signal structure (ps2v -> PortSegment to Verilog signal syntax). For each segment, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port segment is set to a constant, the corresponding constant wire segment placeholder is used instead.

Parameters:

  • ps_dict

    (Dict[int, PortSegment]) –

    The PortSegment dictionary to convert. Each key (int) conforms to the index of the associated PortSegment object.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

set

set(
    port_name: str,
    new_signal: SignalOrLogicLevel,
    idx: Union[int, List[int]] = 0,
) -> None

Sets the signal on a port.

Parameters:

  • port_name

    (str) –

    The name of the port to set the signal on.

  • new_signal

    (Signal) –

    The new signal value.

  • idx

    (Union[int, List[int]], default: 0 ) –

    The index (or indices) to apply the given signal to. Can either be an integer (single index to set) or an iterable of integers (e.g. a list of indices). For every integer of the iterable the signal value of the corresponding port index is set to the given new_signal. Defaults to 0.

Example

from netlist_carpentry.utils.gate_factory import and_gate module = Module(name='m') a = module.create_port('a', 'input', width=6) instance = and_gate(module, 'inst', A=a)

This sets the value of bit 0 of port A to HIGH

instance.set('A', 1, 0) instance.ports['A'].signal_str 'xxxxx1'

This sets the value of bits 1, 3 and 5 of port A to LOW, leaving the other bits as they already are.

instance.set('A', 0, [1, 3, 5]) instance.ports['A'].signal_str '0x0x01'

get_result_vector

get_result_vector(s1: SignalArray, s2: SignalArray) -> SignalArray

Returns the result of this gate's operation for full signal vectors.

This method provides a unified interface for all binary gates to operate on :class:SignalArray (multi-bit) inputs. The default implementation iterates over each bit index and calls :meth:get_result for bitwise gates (e.g. AndGate, OrGate, XorGate). Gates that operate on the full vectors (e.g. arithmetic gates like Adder, Subtractor, or comparison gates like LessThan) override this method with their vector-level logic.

For comparison gates that produce a single bit from two N-bit inputs (e.g. LessThan, Equal), the output is a 1-bit :class:SignalArray.

Parameters:

Returns:

  • SignalArray ( SignalArray ) –

    The result of this gate's operation on the given signals. For bitwise gates, this has the same width as the inputs. For comparison/reduction gates, this is a 1-bit SignalArray.

signals_in

signals_in(idx: NonNegativeInt = 0) -> Tuple[Signal, Signal]

The input signals of the gate.

Returns:

signal_out

signal_out(idx: NonNegativeInt = 0) -> Signal

The output signal of the gate.

Returns:

  • Signal ( Signal ) –

    The output signal of the gate.

NorGate

Bases: BinaryGate, BaseModel

A NOR gate.

A NOR gate is a gate that produces a LOW output signal if either of its input signals is HIGH. Otherwise, it produces a HIGH output signal.

Methods:

  • change_mutability

    Change the mutability status of this instance and optionally its ports.

  • evaluate

    Evaluates the gate's output signal based on its input signals.

  • all_connections

    Returns a dictionary mapping port names to their corresponding connection paths.

  • model_post_init

    Initializes the gate's ports and connections.

  • connect

    Add connections to the specified port of this instance.

  • disconnect

    Remove an existing connection from a specified port of this instance.

  • get_connection

    Retrieve the connection path associated with a specified port and bit index.

  • modify_connection

    Modify an existing connection within a specified port of this instance.

  • connect_modify

    Add a new connection or modify an existing one within the specified port of this instance.

  • tie_port

    Set a constant signal value for the specified port and bit index.

  • has_tied_ports

    Checks the ports of this instance whether any are tied to constant values.

  • has_tied_inputs

    Checks the input ports of this instance whether any are tied to constant values.

  • has_tied_outputs

    Checks the output ports of this instance whether any are tied to constant values.

  • update_signedness

    Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

  • split

    Performs a bit-wise split on this instance.

  • p2v

    Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

  • ps2v

    Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

  • set

    Sets the signal on a port.

  • get_result_vector

    Returns the result of this gate's operation for full signal vectors.

  • signals_in

    The input signals of the gate.

  • signal_out

    The output signal of the gate.

Attributes:

name instance-attribute

name: str

The name of the element.

!!! Do not modify this variable after instantiating it. Use NetlistElement.set_name() instead. Modifying this variable might lead to inconsistencies later on.

metadata class-attribute instance-attribute

Metadata of a netlist element.

Can be user-defined, or e. g. by Yosys (such as src for the HDL source). Is also grouped by categories, i.e. all metadata from Yosys can be accessed via Module.metadata["yosys"], or via Module.metadata.yosys, which both return a dictionary of all metadata. Read the documentation of MetaDataMixin for more information.

path property

Returns the InstancePath of the netlist element.

The InstancePath object is constructed using the element's type and its raw hierarchical path.

Returns:

  • InstancePath ( InstancePath ) –

    The hierarchical path of the netlist element.

type property

type: EType

The type of the element, which is an instance.

hierarchy_level property

hierarchy_level: int

The level of hierarchy of the element in the design.

The hierarchy level is the number of separators in the element's raw path. For example, a top-level instance has a hierarchy level of 0, while a direct submodule instance has a hierarchy level of 1.

Returns:

  • int ( int ) –

    The hierarchy level of the element.

has_parent property

has_parent: bool

Whether this object has a parent.

circuit property

circuit: 'Circuit'

The circuit object to which this netlist element belongs to.

  • For a module, returns the circuit to which the module belongs.
  • For any other netlist element, recursively returns the circuit of the parent, which ultimately leads to a module, to which the netlist element belongs.

Raises:

  • ParentNotFoundError

    If a parent cannot be resolved somewhere in the hierarchical chain.

  • ObjectNotFoundError

    If for a module no circuit is set.

has_circuit property

has_circuit: bool

Whether this netlist element has a defined circuit it belongs to.

Tries to access self.circuit and returns whether the call was successful. Can be used instead of a try-except clause around the call to NetlistElement.circuit.

locked property

locked: bool

True if this NetlistElement instance is locked (i.e. it is currently structurally unchangeable), False if it is mutable.

Can be changed via NetlistElement.change_mutability(bool).

Immutability is used to prevent accidental changes to the design.

is_placeholder_instance property

is_placeholder_instance: bool

A placeholder represents an element that does not have a specific path.

True if this NetlistElement instance represents a placeholder, False otherwise.

can_carry_signal property

can_carry_signal: bool

Whether this exact object is able to receive, pass or hold signal values.

True for ports (as they drive or receive values) and wires (as they pass the signals from driver to load ports) as well as their respective segments. False for instances and modules.

connections property

connections: Dict[str, Dict[int, WireSegmentPath]]

A dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port. Elements with no connection (i.e. the path is None) are excluded. In case these are needed, use Instance.get_connections() instead.

Example

{ 'port1': {1: WireSegmentPath('path/to/element1'), 2: WireSegmentPath('path/to/element2')}, 'port2': {1: WireSegmentPath('path/to/element3')} }

connection_str_paths property

connection_str_paths: Dict[str, Dict[int, str]]

Returns a dictionary mapping port names to their corresponding connection paths as strings.

The keys are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are the raw string paths.

Example

{ 'port1': {0: 'path.to.element1', 1: 'path.to.element2'}, 'port2': {0: 'path.to.element3'} }

ports property

A dictionary mapping port names to their corresponding Port objects.

The keys of the dictionary are the names of the ports. The values are Port objects representing the ports.

Returns:

input_ports property

input_ports: Tuple[Port[Instance], Port[Instance]]

The input ports of the gate as a 2-tuple.

output_ports property

output_ports: Tuple[Port[Instance], ...]

Returns a tuple of output ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as outputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the output ports.

has_unconnected_port_segments property

has_unconnected_port_segments: bool

Returns True if the instance has at least one unconnected port segment.

signals property

signals: Dict[str, SignalArray]

A dictionary with all signals currently present on all ports of this instance.

is_blackbox property

is_blackbox: bool

Flag indicating whether the instance represents neither a primitive element nor a module instance.

If True, this instance does not have a module definition, and is also not a basic component (i.e. a primitive gate instance) from the internal gate library, such as a gate or flip-flop.

y_width property

y_width: PositiveInt

Width of the gate, based on a certain port's width, depending on the actual gate.

a_width property

a_width: PositiveInt

Width of the gate's A port.

b_width property

b_width: PositiveInt

Width of the gate's B port.

is_combinational property

is_combinational: bool

Whether instances of this gate are considered combinational gates.

True for combinational gates, such as AND gates or arithmetic gates. False for flip-flops and latches.

is_sequential property

is_sequential: bool

Whether instances of this gate are considered sequential gates.

False for combinational gates, such as AND gates or arithmetic gates. True for flip-flops and latches.

output_port property

output_port: Port[Instance]

The output port of the gate.

data_width property

data_width: int

The data width of this instance.

Defaults to the data width of the output port. Can be overwritten in extended classes.

In contrast to self.width, which is used for the creation and initialization, this property is linked to the data width of the output port. This property is useful when the data width of the output port can be changed.

a_signed property

a_signed: bool

The signedness of input port A.

b_signed property

b_signed: bool

The signedness of input port B.

truth_table property

truth_table: Dict[Tuple[Signal, Signal], Signal]

A simple truth table as a dictionary.

This dictionary contains the input-output mapping for unary gates that evaluate bitwise (e.g. AndGate, OrGate). Not implemented for arithmetic gates (e.g. Adder).

change_mutability

change_mutability(is_now_locked: bool, recursive: bool = False) -> Self

Change the mutability status of this instance and optionally its ports.

This method allows setting whether this instance can be modified or not. If recursive is set to True, it also applies the same mutability status to all ports of this instance.

Parameters:

  • is_now_locked

    (bool) –

    The new mutability status for this instance.

  • recursive

    (bool, default: False ) –

    Whether to apply the change recursively to its ports. Defaults to False.

evaluate

evaluate() -> None

Evaluates the gate's output signal based on its input signals.

This method is called when the gate's input signals change, and it updates the gate's output signal accordingly.

all_connections

all_connections(
    include_unconnected: bool,
) -> Dict[str, Dict[int, WireSegmentPath]]

Returns a dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port.

Parameters:

  • include_unconnected

    (bool) –

    Whether to include unconnected ports in the result.

Returns:

model_post_init

model_post_init(__context: object) -> None

Initializes the gate's ports and connections.

This method is called after the gate's attributes have been initialized, and it sets up the gate's ports and connections.

connect

connect(
    port_name: str,
    ws_path: Optional[WireSegmentPath],
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add connections to the specified port of this instance.

This method can establish multiple connections if a range of indices is provided.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection(s) should be established.

  • ws_path

    (Optional[WireSegmentPath]) –

    The path of the wire segment that will be connected to this port. If None, the associated port (segment) remains unconnected.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

Raises:

  • ObjectLockedError

    If this instance is currently locked, and no connection can be made.

disconnect

disconnect(port_name: str, index: Optional[int] = None) -> None

Remove an existing connection from a specified port of this instance.

This method disconnects the wire segment at the given index within the specified port_name.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be removed.

  • index

    (Optional[int], default: None ) –

    The bit index within the port for this disconnection. Defaults to None, which completely disconnects the port.

Raises:

get_connection

get_connection(
    port_name: str, index: Optional[NonNegativeInt] = None
) -> Union[WireSegmentPath, Dict[int, WireSegmentPath], None]

Retrieve the connection path associated with a specified port and bit index.

If index is provided, this method returns the wire segment path connected to that specific bit within the port. Otherwise, it returns all connections for the given port as a dictionary mapping indices to WireSegmentPaths.

Parameters:

  • port_name

    (str) –

    The name of the port for which to retrieve the connection(s).

  • index

    (Optional[NonNegativeInt], default: None ) –

    The bit index within the port. Defaults to None.

Returns:

modify_connection

modify_connection(
    port_name: str, ws_path: WireSegmentPath, index: NonNegativeInt = 0
) -> None

Modify an existing connection within a specified port of this instance.

This method updates the wire segment path at the given index within the specified port_name. If the index does not exist yet, it is newly added, changing the width of the port.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be modified.

  • ws_path

    (WireSegmentPath) –

    The new wire segment path for this connection.

  • index

    (NonNegativeInt, default: 0 ) –

    The bit index within the port. Defaults to 0.

connect_modify

connect_modify(
    port_name: str,
    ws_path: WireSegmentPath,
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add a new connection or modify an existing one within the specified port of this instance.

If the connection already exists at the given index and port_name, it will be modified. Otherwise, a new connection is added.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be established or updated.

  • ws_path

    (WireSegmentPath) –

    The path of the wire segment that will be connected to this port.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

tie_port

tie_port(name: str, index: NonNegativeInt, sig_value: LogicLevel) -> None

Set a constant signal value for the specified port and bit index.

If the specified port does not exist, an error message is logged and the function returns False. Otherwise, the method tries to set the constant signal value for that port and returns True if successful.

Does not work for instance output ports, as they are always driven by their parent instances.

Parameters:

  • name

    (str) –

    The name of the port.

  • index

    (NonNegativeInt) –

    The bit index within the port.

  • sig_value

    (LogicLevel) –

    The constant signal value to be set ('0', '1', or 'Z').

Raises:

  • ObjectNotFoundError

    If no such port or port segment exists.

  • AlreadyConnectedError

    (raised by: PortSegment.tie_signal) If this segment is belongs to a load port and is already connected to a wire, from which it receives its value.

  • InvalidDirectionError

    (raised by: PortSegment.tie_signal) If this port segment belongs to an instance output port, which is driven by the instance inputs and the instance's internal logic.

  • InvalidSignalError

    (raised by: PortSegment.tie_signal) If an invalid value is provided.

has_tied_ports

has_tied_ports() -> bool

Checks the ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any ports of this instance are tied to constant values. False otherwise, i.e. all ports are connected to wires.

has_tied_inputs

has_tied_inputs() -> bool

Checks the input ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any input ports of this instance are tied to constant values. False otherwise, i.e. all input ports are connected to wires.

has_tied_outputs

has_tied_outputs() -> bool

Checks the output ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any output ports of this instance are tied to constant values. False otherwise, i.e. all output ports are connected to wires.

update_signedness

update_signedness(port_name: str) -> None

Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

Parameters:

  • port_name

    (str) –

    The name of the port, of which the signedness value is retrieved.

split

split() -> Dict[NonNegativeInt, Self]

Performs a bit-wise split on this instance.

If this instance supports splitting and has a data width of n bit, this method splits this instance into n 1-bit instances. This works for instances, where each output bit depends only on the corresponding input bit(s), e.g. an AND gate or a D-Flipflop.

Returns:

  • Dict[NonNegativeInt, Self]

    Dict[int, Instance]: An n-bit large dictionary, where each key conforms to a bit of the original instance, and each value is an 1-bit instance representing the corresponding "slice" of the original instance.

Raises:

  • SplittingUnsupportedError

    If this instance does not support splitting. Happens for any gate or instance whose behavior depends on the whole bus, and splitting would make it lose its meaning.

p2v

p2v(
    port: ANY_PORT,
    exclude_indices: Optional[List[int]] = None,
    include_indices: Optional[List[int]] = None,
) -> str

Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a Port object and converts them to their corresponding Verilog signal structure (p2v -> Port to Verilog signal syntax). For each segment of the port, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port is set to a constant, the corresponding constant wire segment placeholder is used instead. Port segments can be excluded from the conversion by providing a list of indices to the exclude_indices parameter, indicating which segments should be excluded from the conversion (e.g. segments that are known to be unconnected). Vice versa, only a certain subset of the port's segments may be converted to Verilog syntax, if include_indices is a given list of port indices. All indices not present in the list will be excluded from the conversion.

Parameters:

  • port

    (Port) –

    The Port object to convert.

  • exclude_indices

    (List[int], default: None ) –

    A list of indices to exclude from the conversion. Defaults to None.

  • include_indices

    (List[int], default: None ) –

    A list of indices (i.e. port slices) to include only for the conversion. Defaults to None.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

  • ObjectNotFoundError

    If the wire connected to a certain port segment could not be found.

  • UnsupportedOperationError

    If both exclude_indices and include_indices are specified. Only one of both may be given when calling this method.

ps2v

Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a PortSegment dictionary and converts them to their corresponding Verilog signal structure (ps2v -> PortSegment to Verilog signal syntax). For each segment, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port segment is set to a constant, the corresponding constant wire segment placeholder is used instead.

Parameters:

  • ps_dict

    (Dict[int, PortSegment]) –

    The PortSegment dictionary to convert. Each key (int) conforms to the index of the associated PortSegment object.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

set

set(
    port_name: str,
    new_signal: SignalOrLogicLevel,
    idx: Union[int, List[int]] = 0,
) -> None

Sets the signal on a port.

Parameters:

  • port_name

    (str) –

    The name of the port to set the signal on.

  • new_signal

    (Signal) –

    The new signal value.

  • idx

    (Union[int, List[int]], default: 0 ) –

    The index (or indices) to apply the given signal to. Can either be an integer (single index to set) or an iterable of integers (e.g. a list of indices). For every integer of the iterable the signal value of the corresponding port index is set to the given new_signal. Defaults to 0.

Example

from netlist_carpentry.utils.gate_factory import and_gate module = Module(name='m') a = module.create_port('a', 'input', width=6) instance = and_gate(module, 'inst', A=a)

This sets the value of bit 0 of port A to HIGH

instance.set('A', 1, 0) instance.ports['A'].signal_str 'xxxxx1'

This sets the value of bits 1, 3 and 5 of port A to LOW, leaving the other bits as they already are.

instance.set('A', 0, [1, 3, 5]) instance.ports['A'].signal_str '0x0x01'

get_result_vector

get_result_vector(s1: SignalArray, s2: SignalArray) -> SignalArray

Returns the result of this gate's operation for full signal vectors.

This method provides a unified interface for all binary gates to operate on :class:SignalArray (multi-bit) inputs. The default implementation iterates over each bit index and calls :meth:get_result for bitwise gates (e.g. AndGate, OrGate, XorGate). Gates that operate on the full vectors (e.g. arithmetic gates like Adder, Subtractor, or comparison gates like LessThan) override this method with their vector-level logic.

For comparison gates that produce a single bit from two N-bit inputs (e.g. LessThan, Equal), the output is a 1-bit :class:SignalArray.

Parameters:

Returns:

  • SignalArray ( SignalArray ) –

    The result of this gate's operation on the given signals. For bitwise gates, this has the same width as the inputs. For comparison/reduction gates, this is a 1-bit SignalArray.

signals_in

signals_in(idx: NonNegativeInt = 0) -> Tuple[Signal, Signal]

The input signals of the gate.

Returns:

signal_out

signal_out(idx: NonNegativeInt = 0) -> Signal

The output signal of the gate.

Returns:

  • Signal ( Signal ) –

    The output signal of the gate.

NandGate

Bases: BinaryGate, BaseModel

A NAND gate.

A NAND gate is a gate that produces a LOW output signal only if both its input signals are HIGH. Otherwise, it produces a HIGH output signal.

Methods:

  • change_mutability

    Change the mutability status of this instance and optionally its ports.

  • evaluate

    Evaluates the gate's output signal based on its input signals.

  • all_connections

    Returns a dictionary mapping port names to their corresponding connection paths.

  • model_post_init

    Initializes the gate's ports and connections.

  • connect

    Add connections to the specified port of this instance.

  • disconnect

    Remove an existing connection from a specified port of this instance.

  • get_connection

    Retrieve the connection path associated with a specified port and bit index.

  • modify_connection

    Modify an existing connection within a specified port of this instance.

  • connect_modify

    Add a new connection or modify an existing one within the specified port of this instance.

  • tie_port

    Set a constant signal value for the specified port and bit index.

  • has_tied_ports

    Checks the ports of this instance whether any are tied to constant values.

  • has_tied_inputs

    Checks the input ports of this instance whether any are tied to constant values.

  • has_tied_outputs

    Checks the output ports of this instance whether any are tied to constant values.

  • update_signedness

    Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

  • split

    Performs a bit-wise split on this instance.

  • p2v

    Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

  • ps2v

    Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

  • set

    Sets the signal on a port.

  • get_result_vector

    Returns the result of this gate's operation for full signal vectors.

  • signals_in

    The input signals of the gate.

  • signal_out

    The output signal of the gate.

Attributes:

name instance-attribute

name: str

The name of the element.

!!! Do not modify this variable after instantiating it. Use NetlistElement.set_name() instead. Modifying this variable might lead to inconsistencies later on.

metadata class-attribute instance-attribute

Metadata of a netlist element.

Can be user-defined, or e. g. by Yosys (such as src for the HDL source). Is also grouped by categories, i.e. all metadata from Yosys can be accessed via Module.metadata["yosys"], or via Module.metadata.yosys, which both return a dictionary of all metadata. Read the documentation of MetaDataMixin for more information.

path property

Returns the InstancePath of the netlist element.

The InstancePath object is constructed using the element's type and its raw hierarchical path.

Returns:

  • InstancePath ( InstancePath ) –

    The hierarchical path of the netlist element.

type property

type: EType

The type of the element, which is an instance.

hierarchy_level property

hierarchy_level: int

The level of hierarchy of the element in the design.

The hierarchy level is the number of separators in the element's raw path. For example, a top-level instance has a hierarchy level of 0, while a direct submodule instance has a hierarchy level of 1.

Returns:

  • int ( int ) –

    The hierarchy level of the element.

has_parent property

has_parent: bool

Whether this object has a parent.

circuit property

circuit: 'Circuit'

The circuit object to which this netlist element belongs to.

  • For a module, returns the circuit to which the module belongs.
  • For any other netlist element, recursively returns the circuit of the parent, which ultimately leads to a module, to which the netlist element belongs.

Raises:

  • ParentNotFoundError

    If a parent cannot be resolved somewhere in the hierarchical chain.

  • ObjectNotFoundError

    If for a module no circuit is set.

has_circuit property

has_circuit: bool

Whether this netlist element has a defined circuit it belongs to.

Tries to access self.circuit and returns whether the call was successful. Can be used instead of a try-except clause around the call to NetlistElement.circuit.

locked property

locked: bool

True if this NetlistElement instance is locked (i.e. it is currently structurally unchangeable), False if it is mutable.

Can be changed via NetlistElement.change_mutability(bool).

Immutability is used to prevent accidental changes to the design.

is_placeholder_instance property

is_placeholder_instance: bool

A placeholder represents an element that does not have a specific path.

True if this NetlistElement instance represents a placeholder, False otherwise.

can_carry_signal property

can_carry_signal: bool

Whether this exact object is able to receive, pass or hold signal values.

True for ports (as they drive or receive values) and wires (as they pass the signals from driver to load ports) as well as their respective segments. False for instances and modules.

connections property

connections: Dict[str, Dict[int, WireSegmentPath]]

A dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port. Elements with no connection (i.e. the path is None) are excluded. In case these are needed, use Instance.get_connections() instead.

Example

{ 'port1': {1: WireSegmentPath('path/to/element1'), 2: WireSegmentPath('path/to/element2')}, 'port2': {1: WireSegmentPath('path/to/element3')} }

connection_str_paths property

connection_str_paths: Dict[str, Dict[int, str]]

Returns a dictionary mapping port names to their corresponding connection paths as strings.

The keys are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are the raw string paths.

Example

{ 'port1': {0: 'path.to.element1', 1: 'path.to.element2'}, 'port2': {0: 'path.to.element3'} }

ports property

A dictionary mapping port names to their corresponding Port objects.

The keys of the dictionary are the names of the ports. The values are Port objects representing the ports.

Returns:

input_ports property

input_ports: Tuple[Port[Instance], Port[Instance]]

The input ports of the gate as a 2-tuple.

output_ports property

output_ports: Tuple[Port[Instance], ...]

Returns a tuple of output ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as outputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the output ports.

has_unconnected_port_segments property

has_unconnected_port_segments: bool

Returns True if the instance has at least one unconnected port segment.

signals property

signals: Dict[str, SignalArray]

A dictionary with all signals currently present on all ports of this instance.

is_blackbox property

is_blackbox: bool

Flag indicating whether the instance represents neither a primitive element nor a module instance.

If True, this instance does not have a module definition, and is also not a basic component (i.e. a primitive gate instance) from the internal gate library, such as a gate or flip-flop.

y_width property

y_width: PositiveInt

Width of the gate, based on a certain port's width, depending on the actual gate.

a_width property

a_width: PositiveInt

Width of the gate's A port.

b_width property

b_width: PositiveInt

Width of the gate's B port.

is_combinational property

is_combinational: bool

Whether instances of this gate are considered combinational gates.

True for combinational gates, such as AND gates or arithmetic gates. False for flip-flops and latches.

is_sequential property

is_sequential: bool

Whether instances of this gate are considered sequential gates.

False for combinational gates, such as AND gates or arithmetic gates. True for flip-flops and latches.

output_port property

output_port: Port[Instance]

The output port of the gate.

data_width property

data_width: int

The data width of this instance.

Defaults to the data width of the output port. Can be overwritten in extended classes.

In contrast to self.width, which is used for the creation and initialization, this property is linked to the data width of the output port. This property is useful when the data width of the output port can be changed.

a_signed property

a_signed: bool

The signedness of input port A.

b_signed property

b_signed: bool

The signedness of input port B.

truth_table property

truth_table: Dict[Tuple[Signal, Signal], Signal]

A simple truth table as a dictionary.

This dictionary contains the input-output mapping for unary gates that evaluate bitwise (e.g. AndGate, OrGate). Not implemented for arithmetic gates (e.g. Adder).

change_mutability

change_mutability(is_now_locked: bool, recursive: bool = False) -> Self

Change the mutability status of this instance and optionally its ports.

This method allows setting whether this instance can be modified or not. If recursive is set to True, it also applies the same mutability status to all ports of this instance.

Parameters:

  • is_now_locked

    (bool) –

    The new mutability status for this instance.

  • recursive

    (bool, default: False ) –

    Whether to apply the change recursively to its ports. Defaults to False.

evaluate

evaluate() -> None

Evaluates the gate's output signal based on its input signals.

This method is called when the gate's input signals change, and it updates the gate's output signal accordingly.

all_connections

all_connections(
    include_unconnected: bool,
) -> Dict[str, Dict[int, WireSegmentPath]]

Returns a dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port.

Parameters:

  • include_unconnected

    (bool) –

    Whether to include unconnected ports in the result.

Returns:

model_post_init

model_post_init(__context: object) -> None

Initializes the gate's ports and connections.

This method is called after the gate's attributes have been initialized, and it sets up the gate's ports and connections.

connect

connect(
    port_name: str,
    ws_path: Optional[WireSegmentPath],
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add connections to the specified port of this instance.

This method can establish multiple connections if a range of indices is provided.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection(s) should be established.

  • ws_path

    (Optional[WireSegmentPath]) –

    The path of the wire segment that will be connected to this port. If None, the associated port (segment) remains unconnected.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

Raises:

  • ObjectLockedError

    If this instance is currently locked, and no connection can be made.

disconnect

disconnect(port_name: str, index: Optional[int] = None) -> None

Remove an existing connection from a specified port of this instance.

This method disconnects the wire segment at the given index within the specified port_name.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be removed.

  • index

    (Optional[int], default: None ) –

    The bit index within the port for this disconnection. Defaults to None, which completely disconnects the port.

Raises:

get_connection

get_connection(
    port_name: str, index: Optional[NonNegativeInt] = None
) -> Union[WireSegmentPath, Dict[int, WireSegmentPath], None]

Retrieve the connection path associated with a specified port and bit index.

If index is provided, this method returns the wire segment path connected to that specific bit within the port. Otherwise, it returns all connections for the given port as a dictionary mapping indices to WireSegmentPaths.

Parameters:

  • port_name

    (str) –

    The name of the port for which to retrieve the connection(s).

  • index

    (Optional[NonNegativeInt], default: None ) –

    The bit index within the port. Defaults to None.

Returns:

modify_connection

modify_connection(
    port_name: str, ws_path: WireSegmentPath, index: NonNegativeInt = 0
) -> None

Modify an existing connection within a specified port of this instance.

This method updates the wire segment path at the given index within the specified port_name. If the index does not exist yet, it is newly added, changing the width of the port.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be modified.

  • ws_path

    (WireSegmentPath) –

    The new wire segment path for this connection.

  • index

    (NonNegativeInt, default: 0 ) –

    The bit index within the port. Defaults to 0.

connect_modify

connect_modify(
    port_name: str,
    ws_path: WireSegmentPath,
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add a new connection or modify an existing one within the specified port of this instance.

If the connection already exists at the given index and port_name, it will be modified. Otherwise, a new connection is added.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be established or updated.

  • ws_path

    (WireSegmentPath) –

    The path of the wire segment that will be connected to this port.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

tie_port

tie_port(name: str, index: NonNegativeInt, sig_value: LogicLevel) -> None

Set a constant signal value for the specified port and bit index.

If the specified port does not exist, an error message is logged and the function returns False. Otherwise, the method tries to set the constant signal value for that port and returns True if successful.

Does not work for instance output ports, as they are always driven by their parent instances.

Parameters:

  • name

    (str) –

    The name of the port.

  • index

    (NonNegativeInt) –

    The bit index within the port.

  • sig_value

    (LogicLevel) –

    The constant signal value to be set ('0', '1', or 'Z').

Raises:

  • ObjectNotFoundError

    If no such port or port segment exists.

  • AlreadyConnectedError

    (raised by: PortSegment.tie_signal) If this segment is belongs to a load port and is already connected to a wire, from which it receives its value.

  • InvalidDirectionError

    (raised by: PortSegment.tie_signal) If this port segment belongs to an instance output port, which is driven by the instance inputs and the instance's internal logic.

  • InvalidSignalError

    (raised by: PortSegment.tie_signal) If an invalid value is provided.

has_tied_ports

has_tied_ports() -> bool

Checks the ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any ports of this instance are tied to constant values. False otherwise, i.e. all ports are connected to wires.

has_tied_inputs

has_tied_inputs() -> bool

Checks the input ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any input ports of this instance are tied to constant values. False otherwise, i.e. all input ports are connected to wires.

has_tied_outputs

has_tied_outputs() -> bool

Checks the output ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any output ports of this instance are tied to constant values. False otherwise, i.e. all output ports are connected to wires.

update_signedness

update_signedness(port_name: str) -> None

Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

Parameters:

  • port_name

    (str) –

    The name of the port, of which the signedness value is retrieved.

split

split() -> Dict[NonNegativeInt, Self]

Performs a bit-wise split on this instance.

If this instance supports splitting and has a data width of n bit, this method splits this instance into n 1-bit instances. This works for instances, where each output bit depends only on the corresponding input bit(s), e.g. an AND gate or a D-Flipflop.

Returns:

  • Dict[NonNegativeInt, Self]

    Dict[int, Instance]: An n-bit large dictionary, where each key conforms to a bit of the original instance, and each value is an 1-bit instance representing the corresponding "slice" of the original instance.

Raises:

  • SplittingUnsupportedError

    If this instance does not support splitting. Happens for any gate or instance whose behavior depends on the whole bus, and splitting would make it lose its meaning.

p2v

p2v(
    port: ANY_PORT,
    exclude_indices: Optional[List[int]] = None,
    include_indices: Optional[List[int]] = None,
) -> str

Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a Port object and converts them to their corresponding Verilog signal structure (p2v -> Port to Verilog signal syntax). For each segment of the port, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port is set to a constant, the corresponding constant wire segment placeholder is used instead. Port segments can be excluded from the conversion by providing a list of indices to the exclude_indices parameter, indicating which segments should be excluded from the conversion (e.g. segments that are known to be unconnected). Vice versa, only a certain subset of the port's segments may be converted to Verilog syntax, if include_indices is a given list of port indices. All indices not present in the list will be excluded from the conversion.

Parameters:

  • port

    (Port) –

    The Port object to convert.

  • exclude_indices

    (List[int], default: None ) –

    A list of indices to exclude from the conversion. Defaults to None.

  • include_indices

    (List[int], default: None ) –

    A list of indices (i.e. port slices) to include only for the conversion. Defaults to None.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

  • ObjectNotFoundError

    If the wire connected to a certain port segment could not be found.

  • UnsupportedOperationError

    If both exclude_indices and include_indices are specified. Only one of both may be given when calling this method.

ps2v

Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a PortSegment dictionary and converts them to their corresponding Verilog signal structure (ps2v -> PortSegment to Verilog signal syntax). For each segment, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port segment is set to a constant, the corresponding constant wire segment placeholder is used instead.

Parameters:

  • ps_dict

    (Dict[int, PortSegment]) –

    The PortSegment dictionary to convert. Each key (int) conforms to the index of the associated PortSegment object.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

set

set(
    port_name: str,
    new_signal: SignalOrLogicLevel,
    idx: Union[int, List[int]] = 0,
) -> None

Sets the signal on a port.

Parameters:

  • port_name

    (str) –

    The name of the port to set the signal on.

  • new_signal

    (Signal) –

    The new signal value.

  • idx

    (Union[int, List[int]], default: 0 ) –

    The index (or indices) to apply the given signal to. Can either be an integer (single index to set) or an iterable of integers (e.g. a list of indices). For every integer of the iterable the signal value of the corresponding port index is set to the given new_signal. Defaults to 0.

Example

from netlist_carpentry.utils.gate_factory import and_gate module = Module(name='m') a = module.create_port('a', 'input', width=6) instance = and_gate(module, 'inst', A=a)

This sets the value of bit 0 of port A to HIGH

instance.set('A', 1, 0) instance.ports['A'].signal_str 'xxxxx1'

This sets the value of bits 1, 3 and 5 of port A to LOW, leaving the other bits as they already are.

instance.set('A', 0, [1, 3, 5]) instance.ports['A'].signal_str '0x0x01'

get_result_vector

get_result_vector(s1: SignalArray, s2: SignalArray) -> SignalArray

Returns the result of this gate's operation for full signal vectors.

This method provides a unified interface for all binary gates to operate on :class:SignalArray (multi-bit) inputs. The default implementation iterates over each bit index and calls :meth:get_result for bitwise gates (e.g. AndGate, OrGate, XorGate). Gates that operate on the full vectors (e.g. arithmetic gates like Adder, Subtractor, or comparison gates like LessThan) override this method with their vector-level logic.

For comparison gates that produce a single bit from two N-bit inputs (e.g. LessThan, Equal), the output is a 1-bit :class:SignalArray.

Parameters:

Returns:

  • SignalArray ( SignalArray ) –

    The result of this gate's operation on the given signals. For bitwise gates, this has the same width as the inputs. For comparison/reduction gates, this is a 1-bit SignalArray.

signals_in

signals_in(idx: NonNegativeInt = 0) -> Tuple[Signal, Signal]

The input signals of the gate.

Returns:

signal_out

signal_out(idx: NonNegativeInt = 0) -> Signal

The output signal of the gate.

Returns:

  • Signal ( Signal ) –

    The output signal of the gate.

BitwiseCaseEquality

Bases: BinaryGate, BaseModel

A BITWISE CASE EQUALITY gate.

A BITWISE CASE EQUALITY gate is a gate that compares the input vectors bit by bit and produces a HIGH output signal for a certain bit only if both its input signals are HIGH. Otherwise, it produces a LOW output signal.

Methods:

  • change_mutability

    Change the mutability status of this instance and optionally its ports.

  • evaluate

    Evaluates the gate's output signal based on its input signals.

  • all_connections

    Returns a dictionary mapping port names to their corresponding connection paths.

  • model_post_init

    Initializes the gate's ports and connections.

  • connect

    Add connections to the specified port of this instance.

  • disconnect

    Remove an existing connection from a specified port of this instance.

  • get_connection

    Retrieve the connection path associated with a specified port and bit index.

  • modify_connection

    Modify an existing connection within a specified port of this instance.

  • connect_modify

    Add a new connection or modify an existing one within the specified port of this instance.

  • tie_port

    Set a constant signal value for the specified port and bit index.

  • has_tied_ports

    Checks the ports of this instance whether any are tied to constant values.

  • has_tied_inputs

    Checks the input ports of this instance whether any are tied to constant values.

  • has_tied_outputs

    Checks the output ports of this instance whether any are tied to constant values.

  • update_signedness

    Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

  • split

    Performs a bit-wise split on this instance.

  • p2v

    Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

  • ps2v

    Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

  • set

    Sets the signal on a port.

  • get_result_vector

    Returns the result of this gate's operation for full signal vectors.

  • signals_in

    The input signals of the gate.

  • signal_out

    The output signal of the gate.

Attributes:

name instance-attribute

name: str

The name of the element.

!!! Do not modify this variable after instantiating it. Use NetlistElement.set_name() instead. Modifying this variable might lead to inconsistencies later on.

metadata class-attribute instance-attribute

Metadata of a netlist element.

Can be user-defined, or e. g. by Yosys (such as src for the HDL source). Is also grouped by categories, i.e. all metadata from Yosys can be accessed via Module.metadata["yosys"], or via Module.metadata.yosys, which both return a dictionary of all metadata. Read the documentation of MetaDataMixin for more information.

path property

Returns the InstancePath of the netlist element.

The InstancePath object is constructed using the element's type and its raw hierarchical path.

Returns:

  • InstancePath ( InstancePath ) –

    The hierarchical path of the netlist element.

type property

type: EType

The type of the element, which is an instance.

hierarchy_level property

hierarchy_level: int

The level of hierarchy of the element in the design.

The hierarchy level is the number of separators in the element's raw path. For example, a top-level instance has a hierarchy level of 0, while a direct submodule instance has a hierarchy level of 1.

Returns:

  • int ( int ) –

    The hierarchy level of the element.

has_parent property

has_parent: bool

Whether this object has a parent.

circuit property

circuit: 'Circuit'

The circuit object to which this netlist element belongs to.

  • For a module, returns the circuit to which the module belongs.
  • For any other netlist element, recursively returns the circuit of the parent, which ultimately leads to a module, to which the netlist element belongs.

Raises:

  • ParentNotFoundError

    If a parent cannot be resolved somewhere in the hierarchical chain.

  • ObjectNotFoundError

    If for a module no circuit is set.

has_circuit property

has_circuit: bool

Whether this netlist element has a defined circuit it belongs to.

Tries to access self.circuit and returns whether the call was successful. Can be used instead of a try-except clause around the call to NetlistElement.circuit.

locked property

locked: bool

True if this NetlistElement instance is locked (i.e. it is currently structurally unchangeable), False if it is mutable.

Can be changed via NetlistElement.change_mutability(bool).

Immutability is used to prevent accidental changes to the design.

is_placeholder_instance property

is_placeholder_instance: bool

A placeholder represents an element that does not have a specific path.

True if this NetlistElement instance represents a placeholder, False otherwise.

can_carry_signal property

can_carry_signal: bool

Whether this exact object is able to receive, pass or hold signal values.

True for ports (as they drive or receive values) and wires (as they pass the signals from driver to load ports) as well as their respective segments. False for instances and modules.

connections property

connections: Dict[str, Dict[int, WireSegmentPath]]

A dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port. Elements with no connection (i.e. the path is None) are excluded. In case these are needed, use Instance.get_connections() instead.

Example

{ 'port1': {1: WireSegmentPath('path/to/element1'), 2: WireSegmentPath('path/to/element2')}, 'port2': {1: WireSegmentPath('path/to/element3')} }

connection_str_paths property

connection_str_paths: Dict[str, Dict[int, str]]

Returns a dictionary mapping port names to their corresponding connection paths as strings.

The keys are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are the raw string paths.

Example

{ 'port1': {0: 'path.to.element1', 1: 'path.to.element2'}, 'port2': {0: 'path.to.element3'} }

ports property

A dictionary mapping port names to their corresponding Port objects.

The keys of the dictionary are the names of the ports. The values are Port objects representing the ports.

Returns:

input_ports property

input_ports: Tuple[Port[Instance], Port[Instance]]

The input ports of the gate as a 2-tuple.

output_ports property

output_ports: Tuple[Port[Instance], ...]

Returns a tuple of output ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as outputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the output ports.

has_unconnected_port_segments property

has_unconnected_port_segments: bool

Returns True if the instance has at least one unconnected port segment.

signals property

signals: Dict[str, SignalArray]

A dictionary with all signals currently present on all ports of this instance.

is_blackbox property

is_blackbox: bool

Flag indicating whether the instance represents neither a primitive element nor a module instance.

If True, this instance does not have a module definition, and is also not a basic component (i.e. a primitive gate instance) from the internal gate library, such as a gate or flip-flop.

y_width property

y_width: PositiveInt

Width of the gate, based on a certain port's width, depending on the actual gate.

a_width property

a_width: PositiveInt

Width of the gate's A port.

b_width property

b_width: PositiveInt

Width of the gate's B port.

is_combinational property

is_combinational: bool

Whether instances of this gate are considered combinational gates.

True for combinational gates, such as AND gates or arithmetic gates. False for flip-flops and latches.

is_sequential property

is_sequential: bool

Whether instances of this gate are considered sequential gates.

False for combinational gates, such as AND gates or arithmetic gates. True for flip-flops and latches.

output_port property

output_port: Port[Instance]

The output port of the gate.

data_width property

data_width: int

The data width of this instance.

Defaults to the data width of the output port. Can be overwritten in extended classes.

In contrast to self.width, which is used for the creation and initialization, this property is linked to the data width of the output port. This property is useful when the data width of the output port can be changed.

a_signed property

a_signed: bool

The signedness of input port A.

b_signed property

b_signed: bool

The signedness of input port B.

truth_table property

truth_table: Dict[Tuple[Signal, Signal], Signal]

A simple truth table as a dictionary.

This dictionary contains the input-output mapping for unary gates that evaluate bitwise (e.g. AndGate, OrGate). Not implemented for arithmetic gates (e.g. Adder).

change_mutability

change_mutability(is_now_locked: bool, recursive: bool = False) -> Self

Change the mutability status of this instance and optionally its ports.

This method allows setting whether this instance can be modified or not. If recursive is set to True, it also applies the same mutability status to all ports of this instance.

Parameters:

  • is_now_locked

    (bool) –

    The new mutability status for this instance.

  • recursive

    (bool, default: False ) –

    Whether to apply the change recursively to its ports. Defaults to False.

evaluate

evaluate() -> None

Evaluates the gate's output signal based on its input signals.

This method is called when the gate's input signals change, and it updates the gate's output signal accordingly.

all_connections

all_connections(
    include_unconnected: bool,
) -> Dict[str, Dict[int, WireSegmentPath]]

Returns a dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port.

Parameters:

  • include_unconnected

    (bool) –

    Whether to include unconnected ports in the result.

Returns:

model_post_init

model_post_init(__context: object) -> None

Initializes the gate's ports and connections.

This method is called after the gate's attributes have been initialized, and it sets up the gate's ports and connections.

connect

connect(
    port_name: str,
    ws_path: Optional[WireSegmentPath],
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add connections to the specified port of this instance.

This method can establish multiple connections if a range of indices is provided.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection(s) should be established.

  • ws_path

    (Optional[WireSegmentPath]) –

    The path of the wire segment that will be connected to this port. If None, the associated port (segment) remains unconnected.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

Raises:

  • ObjectLockedError

    If this instance is currently locked, and no connection can be made.

disconnect

disconnect(port_name: str, index: Optional[int] = None) -> None

Remove an existing connection from a specified port of this instance.

This method disconnects the wire segment at the given index within the specified port_name.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be removed.

  • index

    (Optional[int], default: None ) –

    The bit index within the port for this disconnection. Defaults to None, which completely disconnects the port.

Raises:

get_connection

get_connection(
    port_name: str, index: Optional[NonNegativeInt] = None
) -> Union[WireSegmentPath, Dict[int, WireSegmentPath], None]

Retrieve the connection path associated with a specified port and bit index.

If index is provided, this method returns the wire segment path connected to that specific bit within the port. Otherwise, it returns all connections for the given port as a dictionary mapping indices to WireSegmentPaths.

Parameters:

  • port_name

    (str) –

    The name of the port for which to retrieve the connection(s).

  • index

    (Optional[NonNegativeInt], default: None ) –

    The bit index within the port. Defaults to None.

Returns:

modify_connection

modify_connection(
    port_name: str, ws_path: WireSegmentPath, index: NonNegativeInt = 0
) -> None

Modify an existing connection within a specified port of this instance.

This method updates the wire segment path at the given index within the specified port_name. If the index does not exist yet, it is newly added, changing the width of the port.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be modified.

  • ws_path

    (WireSegmentPath) –

    The new wire segment path for this connection.

  • index

    (NonNegativeInt, default: 0 ) –

    The bit index within the port. Defaults to 0.

connect_modify

connect_modify(
    port_name: str,
    ws_path: WireSegmentPath,
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add a new connection or modify an existing one within the specified port of this instance.

If the connection already exists at the given index and port_name, it will be modified. Otherwise, a new connection is added.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be established or updated.

  • ws_path

    (WireSegmentPath) –

    The path of the wire segment that will be connected to this port.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

tie_port

tie_port(name: str, index: NonNegativeInt, sig_value: LogicLevel) -> None

Set a constant signal value for the specified port and bit index.

If the specified port does not exist, an error message is logged and the function returns False. Otherwise, the method tries to set the constant signal value for that port and returns True if successful.

Does not work for instance output ports, as they are always driven by their parent instances.

Parameters:

  • name

    (str) –

    The name of the port.

  • index

    (NonNegativeInt) –

    The bit index within the port.

  • sig_value

    (LogicLevel) –

    The constant signal value to be set ('0', '1', or 'Z').

Raises:

  • ObjectNotFoundError

    If no such port or port segment exists.

  • AlreadyConnectedError

    (raised by: PortSegment.tie_signal) If this segment is belongs to a load port and is already connected to a wire, from which it receives its value.

  • InvalidDirectionError

    (raised by: PortSegment.tie_signal) If this port segment belongs to an instance output port, which is driven by the instance inputs and the instance's internal logic.

  • InvalidSignalError

    (raised by: PortSegment.tie_signal) If an invalid value is provided.

has_tied_ports

has_tied_ports() -> bool

Checks the ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any ports of this instance are tied to constant values. False otherwise, i.e. all ports are connected to wires.

has_tied_inputs

has_tied_inputs() -> bool

Checks the input ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any input ports of this instance are tied to constant values. False otherwise, i.e. all input ports are connected to wires.

has_tied_outputs

has_tied_outputs() -> bool

Checks the output ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any output ports of this instance are tied to constant values. False otherwise, i.e. all output ports are connected to wires.

update_signedness

update_signedness(port_name: str) -> None

Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

Parameters:

  • port_name

    (str) –

    The name of the port, of which the signedness value is retrieved.

split

split() -> Dict[NonNegativeInt, Self]

Performs a bit-wise split on this instance.

If this instance supports splitting and has a data width of n bit, this method splits this instance into n 1-bit instances. This works for instances, where each output bit depends only on the corresponding input bit(s), e.g. an AND gate or a D-Flipflop.

Returns:

  • Dict[NonNegativeInt, Self]

    Dict[int, Instance]: An n-bit large dictionary, where each key conforms to a bit of the original instance, and each value is an 1-bit instance representing the corresponding "slice" of the original instance.

Raises:

  • SplittingUnsupportedError

    If this instance does not support splitting. Happens for any gate or instance whose behavior depends on the whole bus, and splitting would make it lose its meaning.

p2v

p2v(
    port: ANY_PORT,
    exclude_indices: Optional[List[int]] = None,
    include_indices: Optional[List[int]] = None,
) -> str

Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a Port object and converts them to their corresponding Verilog signal structure (p2v -> Port to Verilog signal syntax). For each segment of the port, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port is set to a constant, the corresponding constant wire segment placeholder is used instead. Port segments can be excluded from the conversion by providing a list of indices to the exclude_indices parameter, indicating which segments should be excluded from the conversion (e.g. segments that are known to be unconnected). Vice versa, only a certain subset of the port's segments may be converted to Verilog syntax, if include_indices is a given list of port indices. All indices not present in the list will be excluded from the conversion.

Parameters:

  • port

    (Port) –

    The Port object to convert.

  • exclude_indices

    (List[int], default: None ) –

    A list of indices to exclude from the conversion. Defaults to None.

  • include_indices

    (List[int], default: None ) –

    A list of indices (i.e. port slices) to include only for the conversion. Defaults to None.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

  • ObjectNotFoundError

    If the wire connected to a certain port segment could not be found.

  • UnsupportedOperationError

    If both exclude_indices and include_indices are specified. Only one of both may be given when calling this method.

ps2v

Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a PortSegment dictionary and converts them to their corresponding Verilog signal structure (ps2v -> PortSegment to Verilog signal syntax). For each segment, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port segment is set to a constant, the corresponding constant wire segment placeholder is used instead.

Parameters:

  • ps_dict

    (Dict[int, PortSegment]) –

    The PortSegment dictionary to convert. Each key (int) conforms to the index of the associated PortSegment object.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

set

set(
    port_name: str,
    new_signal: SignalOrLogicLevel,
    idx: Union[int, List[int]] = 0,
) -> None

Sets the signal on a port.

Parameters:

  • port_name

    (str) –

    The name of the port to set the signal on.

  • new_signal

    (Signal) –

    The new signal value.

  • idx

    (Union[int, List[int]], default: 0 ) –

    The index (or indices) to apply the given signal to. Can either be an integer (single index to set) or an iterable of integers (e.g. a list of indices). For every integer of the iterable the signal value of the corresponding port index is set to the given new_signal. Defaults to 0.

Example

from netlist_carpentry.utils.gate_factory import and_gate module = Module(name='m') a = module.create_port('a', 'input', width=6) instance = and_gate(module, 'inst', A=a)

This sets the value of bit 0 of port A to HIGH

instance.set('A', 1, 0) instance.ports['A'].signal_str 'xxxxx1'

This sets the value of bits 1, 3 and 5 of port A to LOW, leaving the other bits as they already are.

instance.set('A', 0, [1, 3, 5]) instance.ports['A'].signal_str '0x0x01'

get_result_vector

get_result_vector(s1: SignalArray, s2: SignalArray) -> SignalArray

Returns the result of this gate's operation for full signal vectors.

This method provides a unified interface for all binary gates to operate on :class:SignalArray (multi-bit) inputs. The default implementation iterates over each bit index and calls :meth:get_result for bitwise gates (e.g. AndGate, OrGate, XorGate). Gates that operate on the full vectors (e.g. arithmetic gates like Adder, Subtractor, or comparison gates like LessThan) override this method with their vector-level logic.

For comparison gates that produce a single bit from two N-bit inputs (e.g. LessThan, Equal), the output is a 1-bit :class:SignalArray.

Parameters:

Returns:

  • SignalArray ( SignalArray ) –

    The result of this gate's operation on the given signals. For bitwise gates, this has the same width as the inputs. For comparison/reduction gates, this is a 1-bit SignalArray.

signals_in

signals_in(idx: NonNegativeInt = 0) -> Tuple[Signal, Signal]

The input signals of the gate.

Returns:

signal_out

signal_out(idx: NonNegativeInt = 0) -> Signal

The output signal of the gate.

Returns:

  • Signal ( Signal ) –

    The output signal of the gate.

ShiftSigned

Bases: ShiftGate, BaseModel

A signed SHIFT gate.

A signed SHIFT gate is a gate that returns its left input shifted right by the number on the right side if it is positive or unsigned, and shifted left by the number on the right side if it is negative.

Methods:

  • change_mutability

    Change the mutability status of this instance and optionally its ports.

  • evaluate

    Evaluates the gate's output signal based on its input signals.

  • all_connections

    Returns a dictionary mapping port names to their corresponding connection paths.

  • model_post_init

    Initializes the gate's ports and connections.

  • connect

    Add connections to the specified port of this instance.

  • disconnect

    Remove an existing connection from a specified port of this instance.

  • get_connection

    Retrieve the connection path associated with a specified port and bit index.

  • modify_connection

    Modify an existing connection within a specified port of this instance.

  • connect_modify

    Add a new connection or modify an existing one within the specified port of this instance.

  • tie_port

    Set a constant signal value for the specified port and bit index.

  • has_tied_ports

    Checks the ports of this instance whether any are tied to constant values.

  • has_tied_inputs

    Checks the input ports of this instance whether any are tied to constant values.

  • has_tied_outputs

    Checks the output ports of this instance whether any are tied to constant values.

  • update_signedness

    Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

  • split

    Performs a bit-wise split on this instance.

  • p2v

    Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

  • ps2v

    Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

  • set

    Sets the signal on a port.

  • get_result

    Returns the result of this gate's operation for given Signals s1 and s2.

  • signals_in

    The input signals of the gate.

  • signal_out

    The output signal of the gate.

Attributes:

name instance-attribute

name: str

The name of the element.

!!! Do not modify this variable after instantiating it. Use NetlistElement.set_name() instead. Modifying this variable might lead to inconsistencies later on.

metadata class-attribute instance-attribute

Metadata of a netlist element.

Can be user-defined, or e. g. by Yosys (such as src for the HDL source). Is also grouped by categories, i.e. all metadata from Yosys can be accessed via Module.metadata["yosys"], or via Module.metadata.yosys, which both return a dictionary of all metadata. Read the documentation of MetaDataMixin for more information.

path property

Returns the InstancePath of the netlist element.

The InstancePath object is constructed using the element's type and its raw hierarchical path.

Returns:

  • InstancePath ( InstancePath ) –

    The hierarchical path of the netlist element.

type property

type: EType

The type of the element, which is an instance.

hierarchy_level property

hierarchy_level: int

The level of hierarchy of the element in the design.

The hierarchy level is the number of separators in the element's raw path. For example, a top-level instance has a hierarchy level of 0, while a direct submodule instance has a hierarchy level of 1.

Returns:

  • int ( int ) –

    The hierarchy level of the element.

has_parent property

has_parent: bool

Whether this object has a parent.

circuit property

circuit: 'Circuit'

The circuit object to which this netlist element belongs to.

  • For a module, returns the circuit to which the module belongs.
  • For any other netlist element, recursively returns the circuit of the parent, which ultimately leads to a module, to which the netlist element belongs.

Raises:

  • ParentNotFoundError

    If a parent cannot be resolved somewhere in the hierarchical chain.

  • ObjectNotFoundError

    If for a module no circuit is set.

has_circuit property

has_circuit: bool

Whether this netlist element has a defined circuit it belongs to.

Tries to access self.circuit and returns whether the call was successful. Can be used instead of a try-except clause around the call to NetlistElement.circuit.

locked property

locked: bool

True if this NetlistElement instance is locked (i.e. it is currently structurally unchangeable), False if it is mutable.

Can be changed via NetlistElement.change_mutability(bool).

Immutability is used to prevent accidental changes to the design.

is_placeholder_instance property

is_placeholder_instance: bool

A placeholder represents an element that does not have a specific path.

True if this NetlistElement instance represents a placeholder, False otherwise.

can_carry_signal property

can_carry_signal: bool

Whether this exact object is able to receive, pass or hold signal values.

True for ports (as they drive or receive values) and wires (as they pass the signals from driver to load ports) as well as their respective segments. False for instances and modules.

connections property

connections: Dict[str, Dict[int, WireSegmentPath]]

A dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port. Elements with no connection (i.e. the path is None) are excluded. In case these are needed, use Instance.get_connections() instead.

Example

{ 'port1': {1: WireSegmentPath('path/to/element1'), 2: WireSegmentPath('path/to/element2')}, 'port2': {1: WireSegmentPath('path/to/element3')} }

connection_str_paths property

connection_str_paths: Dict[str, Dict[int, str]]

Returns a dictionary mapping port names to their corresponding connection paths as strings.

The keys are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are the raw string paths.

Example

{ 'port1': {0: 'path.to.element1', 1: 'path.to.element2'}, 'port2': {0: 'path.to.element3'} }

ports property

A dictionary mapping port names to their corresponding Port objects.

The keys of the dictionary are the names of the ports. The values are Port objects representing the ports.

Returns:

input_ports property

input_ports: Tuple[Port[Instance], Port[Instance]]

The input ports of the gate as a 2-tuple.

output_ports property

output_ports: Tuple[Port[Instance], ...]

Returns a tuple of output ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as outputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the output ports.

has_unconnected_port_segments property

has_unconnected_port_segments: bool

Returns True if the instance has at least one unconnected port segment.

signals property

signals: Dict[str, SignalArray]

A dictionary with all signals currently present on all ports of this instance.

is_blackbox property

is_blackbox: bool

Flag indicating whether the instance represents neither a primitive element nor a module instance.

If True, this instance does not have a module definition, and is also not a basic component (i.e. a primitive gate instance) from the internal gate library, such as a gate or flip-flop.

y_width property

y_width: PositiveInt

Width of the gate, based on a certain port's width, depending on the actual gate.

a_width property

a_width: PositiveInt

Width of the gate's A port.

b_width property

b_width: PositiveInt

Width of the gate's B port.

is_combinational property

is_combinational: bool

Whether instances of this gate are considered combinational gates.

True for combinational gates, such as AND gates or arithmetic gates. False for flip-flops and latches.

is_sequential property

is_sequential: bool

Whether instances of this gate are considered sequential gates.

False for combinational gates, such as AND gates or arithmetic gates. True for flip-flops and latches.

output_port property

output_port: Port[Instance]

The output port of the gate.

data_width property

data_width: int

The data width of this instance.

Defaults to the data width of the output port. Can be overwritten in extended classes.

In contrast to self.width, which is used for the creation and initialization, this property is linked to the data width of the output port. This property is useful when the data width of the output port can be changed.

a_signed property

a_signed: bool

The signedness of input port A.

b_signed property

b_signed: bool

The signedness of input port B.

truth_table property

truth_table: Dict[Tuple[Signal, Signal], Signal]

A simple truth table as a dictionary.

This dictionary contains the input-output mapping for unary gates that evaluate bitwise (e.g. AndGate, OrGate). Not implemented for arithmetic gates (e.g. Adder).

change_mutability

change_mutability(is_now_locked: bool, recursive: bool = False) -> Self

Change the mutability status of this instance and optionally its ports.

This method allows setting whether this instance can be modified or not. If recursive is set to True, it also applies the same mutability status to all ports of this instance.

Parameters:

  • is_now_locked

    (bool) –

    The new mutability status for this instance.

  • recursive

    (bool, default: False ) –

    Whether to apply the change recursively to its ports. Defaults to False.

evaluate

evaluate() -> None

Evaluates the gate's output signal based on its input signals.

This method is called when the gate's input signals change, and it updates the gate's output signal accordingly.

all_connections

all_connections(
    include_unconnected: bool,
) -> Dict[str, Dict[int, WireSegmentPath]]

Returns a dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port.

Parameters:

  • include_unconnected

    (bool) –

    Whether to include unconnected ports in the result.

Returns:

model_post_init

model_post_init(__context: object) -> None

Initializes the gate's ports and connections.

This method is called after the gate's attributes have been initialized, and it sets up the gate's ports and connections.

connect

connect(
    port_name: str,
    ws_path: Optional[WireSegmentPath],
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add connections to the specified port of this instance.

This method can establish multiple connections if a range of indices is provided.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection(s) should be established.

  • ws_path

    (Optional[WireSegmentPath]) –

    The path of the wire segment that will be connected to this port. If None, the associated port (segment) remains unconnected.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

Raises:

  • ObjectLockedError

    If this instance is currently locked, and no connection can be made.

disconnect

disconnect(port_name: str, index: Optional[int] = None) -> None

Remove an existing connection from a specified port of this instance.

This method disconnects the wire segment at the given index within the specified port_name.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be removed.

  • index

    (Optional[int], default: None ) –

    The bit index within the port for this disconnection. Defaults to None, which completely disconnects the port.

Raises:

get_connection

get_connection(
    port_name: str, index: Optional[NonNegativeInt] = None
) -> Union[WireSegmentPath, Dict[int, WireSegmentPath], None]

Retrieve the connection path associated with a specified port and bit index.

If index is provided, this method returns the wire segment path connected to that specific bit within the port. Otherwise, it returns all connections for the given port as a dictionary mapping indices to WireSegmentPaths.

Parameters:

  • port_name

    (str) –

    The name of the port for which to retrieve the connection(s).

  • index

    (Optional[NonNegativeInt], default: None ) –

    The bit index within the port. Defaults to None.

Returns:

modify_connection

modify_connection(
    port_name: str, ws_path: WireSegmentPath, index: NonNegativeInt = 0
) -> None

Modify an existing connection within a specified port of this instance.

This method updates the wire segment path at the given index within the specified port_name. If the index does not exist yet, it is newly added, changing the width of the port.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be modified.

  • ws_path

    (WireSegmentPath) –

    The new wire segment path for this connection.

  • index

    (NonNegativeInt, default: 0 ) –

    The bit index within the port. Defaults to 0.

connect_modify

connect_modify(
    port_name: str,
    ws_path: WireSegmentPath,
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add a new connection or modify an existing one within the specified port of this instance.

If the connection already exists at the given index and port_name, it will be modified. Otherwise, a new connection is added.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be established or updated.

  • ws_path

    (WireSegmentPath) –

    The path of the wire segment that will be connected to this port.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

tie_port

tie_port(name: str, index: NonNegativeInt, sig_value: LogicLevel) -> None

Set a constant signal value for the specified port and bit index.

If the specified port does not exist, an error message is logged and the function returns False. Otherwise, the method tries to set the constant signal value for that port and returns True if successful.

Does not work for instance output ports, as they are always driven by their parent instances.

Parameters:

  • name

    (str) –

    The name of the port.

  • index

    (NonNegativeInt) –

    The bit index within the port.

  • sig_value

    (LogicLevel) –

    The constant signal value to be set ('0', '1', or 'Z').

Raises:

  • ObjectNotFoundError

    If no such port or port segment exists.

  • AlreadyConnectedError

    (raised by: PortSegment.tie_signal) If this segment is belongs to a load port and is already connected to a wire, from which it receives its value.

  • InvalidDirectionError

    (raised by: PortSegment.tie_signal) If this port segment belongs to an instance output port, which is driven by the instance inputs and the instance's internal logic.

  • InvalidSignalError

    (raised by: PortSegment.tie_signal) If an invalid value is provided.

has_tied_ports

has_tied_ports() -> bool

Checks the ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any ports of this instance are tied to constant values. False otherwise, i.e. all ports are connected to wires.

has_tied_inputs

has_tied_inputs() -> bool

Checks the input ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any input ports of this instance are tied to constant values. False otherwise, i.e. all input ports are connected to wires.

has_tied_outputs

has_tied_outputs() -> bool

Checks the output ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any output ports of this instance are tied to constant values. False otherwise, i.e. all output ports are connected to wires.

update_signedness

update_signedness(port_name: str) -> None

Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

Parameters:

  • port_name

    (str) –

    The name of the port, of which the signedness value is retrieved.

split

split() -> Dict[NonNegativeInt, Self]

Performs a bit-wise split on this instance.

If this instance supports splitting and has a data width of n bit, this method splits this instance into n 1-bit instances. This works for instances, where each output bit depends only on the corresponding input bit(s), e.g. an AND gate or a D-Flipflop.

Returns:

  • Dict[NonNegativeInt, Self]

    Dict[int, Instance]: An n-bit large dictionary, where each key conforms to a bit of the original instance, and each value is an 1-bit instance representing the corresponding "slice" of the original instance.

Raises:

  • SplittingUnsupportedError

    If this instance does not support splitting. Happens for any gate or instance whose behavior depends on the whole bus, and splitting would make it lose its meaning.

p2v

p2v(
    port: ANY_PORT,
    exclude_indices: Optional[List[int]] = None,
    include_indices: Optional[List[int]] = None,
) -> str

Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a Port object and converts them to their corresponding Verilog signal structure (p2v -> Port to Verilog signal syntax). For each segment of the port, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port is set to a constant, the corresponding constant wire segment placeholder is used instead. Port segments can be excluded from the conversion by providing a list of indices to the exclude_indices parameter, indicating which segments should be excluded from the conversion (e.g. segments that are known to be unconnected). Vice versa, only a certain subset of the port's segments may be converted to Verilog syntax, if include_indices is a given list of port indices. All indices not present in the list will be excluded from the conversion.

Parameters:

  • port

    (Port) –

    The Port object to convert.

  • exclude_indices

    (List[int], default: None ) –

    A list of indices to exclude from the conversion. Defaults to None.

  • include_indices

    (List[int], default: None ) –

    A list of indices (i.e. port slices) to include only for the conversion. Defaults to None.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

  • ObjectNotFoundError

    If the wire connected to a certain port segment could not be found.

  • UnsupportedOperationError

    If both exclude_indices and include_indices are specified. Only one of both may be given when calling this method.

ps2v

Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a PortSegment dictionary and converts them to their corresponding Verilog signal structure (ps2v -> PortSegment to Verilog signal syntax). For each segment, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port segment is set to a constant, the corresponding constant wire segment placeholder is used instead.

Parameters:

  • ps_dict

    (Dict[int, PortSegment]) –

    The PortSegment dictionary to convert. Each key (int) conforms to the index of the associated PortSegment object.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

set

set(
    port_name: str,
    new_signal: SignalOrLogicLevel,
    idx: Union[int, List[int]] = 0,
) -> None

Sets the signal on a port.

Parameters:

  • port_name

    (str) –

    The name of the port to set the signal on.

  • new_signal

    (Signal) –

    The new signal value.

  • idx

    (Union[int, List[int]], default: 0 ) –

    The index (or indices) to apply the given signal to. Can either be an integer (single index to set) or an iterable of integers (e.g. a list of indices). For every integer of the iterable the signal value of the corresponding port index is set to the given new_signal. Defaults to 0.

Example

from netlist_carpentry.utils.gate_factory import and_gate module = Module(name='m') a = module.create_port('a', 'input', width=6) instance = and_gate(module, 'inst', A=a)

This sets the value of bit 0 of port A to HIGH

instance.set('A', 1, 0) instance.ports['A'].signal_str 'xxxxx1'

This sets the value of bits 1, 3 and 5 of port A to LOW, leaving the other bits as they already are.

instance.set('A', 0, [1, 3, 5]) instance.ports['A'].signal_str '0x0x01'

get_result

get_result(s1: Signal, s2: Signal) -> Signal

Returns the result of this gate's operation for given Signals s1 and s2.

This method is only implemented for bitwise evaluating gates (e.g. AndGate, OrGate). This method raises an UnsupportedOperationError if used on other gates (e.g. Adder).

For vector-level operations on full signal arrays, use :meth:get_result_vector instead.

Parameters:

  • s1

    (Signal) –

    The first Signal, i.e. the first operand.

  • s2

    (Signal) –

    The second Signal, i.e. the second operand.

Raises:

Returns:

  • Signal ( Signal ) –

    The result of this gate's operation on the given signals.

signals_in

signals_in(idx: NonNegativeInt = 0) -> Tuple[Signal, Signal]

The input signals of the gate.

Returns:

signal_out

signal_out(idx: NonNegativeInt = 0) -> Signal

The output signal of the gate.

Returns:

  • Signal ( Signal ) –

    The output signal of the gate.

ShiftLeft

Bases: ShiftGate, BaseModel

A SHIFT-LEFT gate.

A SHIFT-LEFT gate is a gate that returns its left input shifted left by the number on the right side.

Methods:

  • change_mutability

    Change the mutability status of this instance and optionally its ports.

  • evaluate

    Evaluates the gate's output signal based on its input signals.

  • all_connections

    Returns a dictionary mapping port names to their corresponding connection paths.

  • model_post_init

    Initializes the gate's ports and connections.

  • connect

    Add connections to the specified port of this instance.

  • disconnect

    Remove an existing connection from a specified port of this instance.

  • get_connection

    Retrieve the connection path associated with a specified port and bit index.

  • modify_connection

    Modify an existing connection within a specified port of this instance.

  • connect_modify

    Add a new connection or modify an existing one within the specified port of this instance.

  • tie_port

    Set a constant signal value for the specified port and bit index.

  • has_tied_ports

    Checks the ports of this instance whether any are tied to constant values.

  • has_tied_inputs

    Checks the input ports of this instance whether any are tied to constant values.

  • has_tied_outputs

    Checks the output ports of this instance whether any are tied to constant values.

  • update_signedness

    Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

  • split

    Performs a bit-wise split on this instance.

  • p2v

    Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

  • ps2v

    Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

  • set

    Sets the signal on a port.

  • get_result

    Returns the result of this gate's operation for given Signals s1 and s2.

  • signals_in

    The input signals of the gate.

  • signal_out

    The output signal of the gate.

Attributes:

name instance-attribute

name: str

The name of the element.

!!! Do not modify this variable after instantiating it. Use NetlistElement.set_name() instead. Modifying this variable might lead to inconsistencies later on.

metadata class-attribute instance-attribute

Metadata of a netlist element.

Can be user-defined, or e. g. by Yosys (such as src for the HDL source). Is also grouped by categories, i.e. all metadata from Yosys can be accessed via Module.metadata["yosys"], or via Module.metadata.yosys, which both return a dictionary of all metadata. Read the documentation of MetaDataMixin for more information.

path property

Returns the InstancePath of the netlist element.

The InstancePath object is constructed using the element's type and its raw hierarchical path.

Returns:

  • InstancePath ( InstancePath ) –

    The hierarchical path of the netlist element.

type property

type: EType

The type of the element, which is an instance.

hierarchy_level property

hierarchy_level: int

The level of hierarchy of the element in the design.

The hierarchy level is the number of separators in the element's raw path. For example, a top-level instance has a hierarchy level of 0, while a direct submodule instance has a hierarchy level of 1.

Returns:

  • int ( int ) –

    The hierarchy level of the element.

has_parent property

has_parent: bool

Whether this object has a parent.

circuit property

circuit: 'Circuit'

The circuit object to which this netlist element belongs to.

  • For a module, returns the circuit to which the module belongs.
  • For any other netlist element, recursively returns the circuit of the parent, which ultimately leads to a module, to which the netlist element belongs.

Raises:

  • ParentNotFoundError

    If a parent cannot be resolved somewhere in the hierarchical chain.

  • ObjectNotFoundError

    If for a module no circuit is set.

has_circuit property

has_circuit: bool

Whether this netlist element has a defined circuit it belongs to.

Tries to access self.circuit and returns whether the call was successful. Can be used instead of a try-except clause around the call to NetlistElement.circuit.

locked property

locked: bool

True if this NetlistElement instance is locked (i.e. it is currently structurally unchangeable), False if it is mutable.

Can be changed via NetlistElement.change_mutability(bool).

Immutability is used to prevent accidental changes to the design.

is_placeholder_instance property

is_placeholder_instance: bool

A placeholder represents an element that does not have a specific path.

True if this NetlistElement instance represents a placeholder, False otherwise.

can_carry_signal property

can_carry_signal: bool

Whether this exact object is able to receive, pass or hold signal values.

True for ports (as they drive or receive values) and wires (as they pass the signals from driver to load ports) as well as their respective segments. False for instances and modules.

connections property

connections: Dict[str, Dict[int, WireSegmentPath]]

A dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port. Elements with no connection (i.e. the path is None) are excluded. In case these are needed, use Instance.get_connections() instead.

Example

{ 'port1': {1: WireSegmentPath('path/to/element1'), 2: WireSegmentPath('path/to/element2')}, 'port2': {1: WireSegmentPath('path/to/element3')} }

connection_str_paths property

connection_str_paths: Dict[str, Dict[int, str]]

Returns a dictionary mapping port names to their corresponding connection paths as strings.

The keys are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are the raw string paths.

Example

{ 'port1': {0: 'path.to.element1', 1: 'path.to.element2'}, 'port2': {0: 'path.to.element3'} }

ports property

A dictionary mapping port names to their corresponding Port objects.

The keys of the dictionary are the names of the ports. The values are Port objects representing the ports.

Returns:

input_ports property

input_ports: Tuple[Port[Instance], Port[Instance]]

The input ports of the gate as a 2-tuple.

output_ports property

output_ports: Tuple[Port[Instance], ...]

Returns a tuple of output ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as outputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the output ports.

has_unconnected_port_segments property

has_unconnected_port_segments: bool

Returns True if the instance has at least one unconnected port segment.

signals property

signals: Dict[str, SignalArray]

A dictionary with all signals currently present on all ports of this instance.

is_blackbox property

is_blackbox: bool

Flag indicating whether the instance represents neither a primitive element nor a module instance.

If True, this instance does not have a module definition, and is also not a basic component (i.e. a primitive gate instance) from the internal gate library, such as a gate or flip-flop.

y_width property

y_width: PositiveInt

Width of the gate, based on a certain port's width, depending on the actual gate.

a_width property

a_width: PositiveInt

Width of the gate's A port.

b_width property

b_width: PositiveInt

Width of the gate's B port.

is_combinational property

is_combinational: bool

Whether instances of this gate are considered combinational gates.

True for combinational gates, such as AND gates or arithmetic gates. False for flip-flops and latches.

is_sequential property

is_sequential: bool

Whether instances of this gate are considered sequential gates.

False for combinational gates, such as AND gates or arithmetic gates. True for flip-flops and latches.

output_port property

output_port: Port[Instance]

The output port of the gate.

data_width property

data_width: int

The data width of this instance.

Defaults to the data width of the output port. Can be overwritten in extended classes.

In contrast to self.width, which is used for the creation and initialization, this property is linked to the data width of the output port. This property is useful when the data width of the output port can be changed.

a_signed property

a_signed: bool

The signedness of input port A.

b_signed property

b_signed: bool

The signedness of input port B.

truth_table property

truth_table: Dict[Tuple[Signal, Signal], Signal]

A simple truth table as a dictionary.

This dictionary contains the input-output mapping for unary gates that evaluate bitwise (e.g. AndGate, OrGate). Not implemented for arithmetic gates (e.g. Adder).

change_mutability

change_mutability(is_now_locked: bool, recursive: bool = False) -> Self

Change the mutability status of this instance and optionally its ports.

This method allows setting whether this instance can be modified or not. If recursive is set to True, it also applies the same mutability status to all ports of this instance.

Parameters:

  • is_now_locked

    (bool) –

    The new mutability status for this instance.

  • recursive

    (bool, default: False ) –

    Whether to apply the change recursively to its ports. Defaults to False.

evaluate

evaluate() -> None

Evaluates the gate's output signal based on its input signals.

This method is called when the gate's input signals change, and it updates the gate's output signal accordingly.

all_connections

all_connections(
    include_unconnected: bool,
) -> Dict[str, Dict[int, WireSegmentPath]]

Returns a dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port.

Parameters:

  • include_unconnected

    (bool) –

    Whether to include unconnected ports in the result.

Returns:

model_post_init

model_post_init(__context: object) -> None

Initializes the gate's ports and connections.

This method is called after the gate's attributes have been initialized, and it sets up the gate's ports and connections.

connect

connect(
    port_name: str,
    ws_path: Optional[WireSegmentPath],
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add connections to the specified port of this instance.

This method can establish multiple connections if a range of indices is provided.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection(s) should be established.

  • ws_path

    (Optional[WireSegmentPath]) –

    The path of the wire segment that will be connected to this port. If None, the associated port (segment) remains unconnected.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

Raises:

  • ObjectLockedError

    If this instance is currently locked, and no connection can be made.

disconnect

disconnect(port_name: str, index: Optional[int] = None) -> None

Remove an existing connection from a specified port of this instance.

This method disconnects the wire segment at the given index within the specified port_name.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be removed.

  • index

    (Optional[int], default: None ) –

    The bit index within the port for this disconnection. Defaults to None, which completely disconnects the port.

Raises:

get_connection

get_connection(
    port_name: str, index: Optional[NonNegativeInt] = None
) -> Union[WireSegmentPath, Dict[int, WireSegmentPath], None]

Retrieve the connection path associated with a specified port and bit index.

If index is provided, this method returns the wire segment path connected to that specific bit within the port. Otherwise, it returns all connections for the given port as a dictionary mapping indices to WireSegmentPaths.

Parameters:

  • port_name

    (str) –

    The name of the port for which to retrieve the connection(s).

  • index

    (Optional[NonNegativeInt], default: None ) –

    The bit index within the port. Defaults to None.

Returns:

modify_connection

modify_connection(
    port_name: str, ws_path: WireSegmentPath, index: NonNegativeInt = 0
) -> None

Modify an existing connection within a specified port of this instance.

This method updates the wire segment path at the given index within the specified port_name. If the index does not exist yet, it is newly added, changing the width of the port.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be modified.

  • ws_path

    (WireSegmentPath) –

    The new wire segment path for this connection.

  • index

    (NonNegativeInt, default: 0 ) –

    The bit index within the port. Defaults to 0.

connect_modify

connect_modify(
    port_name: str,
    ws_path: WireSegmentPath,
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add a new connection or modify an existing one within the specified port of this instance.

If the connection already exists at the given index and port_name, it will be modified. Otherwise, a new connection is added.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be established or updated.

  • ws_path

    (WireSegmentPath) –

    The path of the wire segment that will be connected to this port.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

tie_port

tie_port(name: str, index: NonNegativeInt, sig_value: LogicLevel) -> None

Set a constant signal value for the specified port and bit index.

If the specified port does not exist, an error message is logged and the function returns False. Otherwise, the method tries to set the constant signal value for that port and returns True if successful.

Does not work for instance output ports, as they are always driven by their parent instances.

Parameters:

  • name

    (str) –

    The name of the port.

  • index

    (NonNegativeInt) –

    The bit index within the port.

  • sig_value

    (LogicLevel) –

    The constant signal value to be set ('0', '1', or 'Z').

Raises:

  • ObjectNotFoundError

    If no such port or port segment exists.

  • AlreadyConnectedError

    (raised by: PortSegment.tie_signal) If this segment is belongs to a load port and is already connected to a wire, from which it receives its value.

  • InvalidDirectionError

    (raised by: PortSegment.tie_signal) If this port segment belongs to an instance output port, which is driven by the instance inputs and the instance's internal logic.

  • InvalidSignalError

    (raised by: PortSegment.tie_signal) If an invalid value is provided.

has_tied_ports

has_tied_ports() -> bool

Checks the ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any ports of this instance are tied to constant values. False otherwise, i.e. all ports are connected to wires.

has_tied_inputs

has_tied_inputs() -> bool

Checks the input ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any input ports of this instance are tied to constant values. False otherwise, i.e. all input ports are connected to wires.

has_tied_outputs

has_tied_outputs() -> bool

Checks the output ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any output ports of this instance are tied to constant values. False otherwise, i.e. all output ports are connected to wires.

update_signedness

update_signedness(port_name: str) -> None

Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

Parameters:

  • port_name

    (str) –

    The name of the port, of which the signedness value is retrieved.

split

split() -> Dict[NonNegativeInt, Self]

Performs a bit-wise split on this instance.

If this instance supports splitting and has a data width of n bit, this method splits this instance into n 1-bit instances. This works for instances, where each output bit depends only on the corresponding input bit(s), e.g. an AND gate or a D-Flipflop.

Returns:

  • Dict[NonNegativeInt, Self]

    Dict[int, Instance]: An n-bit large dictionary, where each key conforms to a bit of the original instance, and each value is an 1-bit instance representing the corresponding "slice" of the original instance.

Raises:

  • SplittingUnsupportedError

    If this instance does not support splitting. Happens for any gate or instance whose behavior depends on the whole bus, and splitting would make it lose its meaning.

p2v

p2v(
    port: ANY_PORT,
    exclude_indices: Optional[List[int]] = None,
    include_indices: Optional[List[int]] = None,
) -> str

Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a Port object and converts them to their corresponding Verilog signal structure (p2v -> Port to Verilog signal syntax). For each segment of the port, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port is set to a constant, the corresponding constant wire segment placeholder is used instead. Port segments can be excluded from the conversion by providing a list of indices to the exclude_indices parameter, indicating which segments should be excluded from the conversion (e.g. segments that are known to be unconnected). Vice versa, only a certain subset of the port's segments may be converted to Verilog syntax, if include_indices is a given list of port indices. All indices not present in the list will be excluded from the conversion.

Parameters:

  • port

    (Port) –

    The Port object to convert.

  • exclude_indices

    (List[int], default: None ) –

    A list of indices to exclude from the conversion. Defaults to None.

  • include_indices

    (List[int], default: None ) –

    A list of indices (i.e. port slices) to include only for the conversion. Defaults to None.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

  • ObjectNotFoundError

    If the wire connected to a certain port segment could not be found.

  • UnsupportedOperationError

    If both exclude_indices and include_indices are specified. Only one of both may be given when calling this method.

ps2v

Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a PortSegment dictionary and converts them to their corresponding Verilog signal structure (ps2v -> PortSegment to Verilog signal syntax). For each segment, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port segment is set to a constant, the corresponding constant wire segment placeholder is used instead.

Parameters:

  • ps_dict

    (Dict[int, PortSegment]) –

    The PortSegment dictionary to convert. Each key (int) conforms to the index of the associated PortSegment object.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

set

set(
    port_name: str,
    new_signal: SignalOrLogicLevel,
    idx: Union[int, List[int]] = 0,
) -> None

Sets the signal on a port.

Parameters:

  • port_name

    (str) –

    The name of the port to set the signal on.

  • new_signal

    (Signal) –

    The new signal value.

  • idx

    (Union[int, List[int]], default: 0 ) –

    The index (or indices) to apply the given signal to. Can either be an integer (single index to set) or an iterable of integers (e.g. a list of indices). For every integer of the iterable the signal value of the corresponding port index is set to the given new_signal. Defaults to 0.

Example

from netlist_carpentry.utils.gate_factory import and_gate module = Module(name='m') a = module.create_port('a', 'input', width=6) instance = and_gate(module, 'inst', A=a)

This sets the value of bit 0 of port A to HIGH

instance.set('A', 1, 0) instance.ports['A'].signal_str 'xxxxx1'

This sets the value of bits 1, 3 and 5 of port A to LOW, leaving the other bits as they already are.

instance.set('A', 0, [1, 3, 5]) instance.ports['A'].signal_str '0x0x01'

get_result

get_result(s1: Signal, s2: Signal) -> Signal

Returns the result of this gate's operation for given Signals s1 and s2.

This method is only implemented for bitwise evaluating gates (e.g. AndGate, OrGate). This method raises an UnsupportedOperationError if used on other gates (e.g. Adder).

For vector-level operations on full signal arrays, use :meth:get_result_vector instead.

Parameters:

  • s1

    (Signal) –

    The first Signal, i.e. the first operand.

  • s2

    (Signal) –

    The second Signal, i.e. the second operand.

Raises:

Returns:

  • Signal ( Signal ) –

    The result of this gate's operation on the given signals.

signals_in

signals_in(idx: NonNegativeInt = 0) -> Tuple[Signal, Signal]

The input signals of the gate.

Returns:

signal_out

signal_out(idx: NonNegativeInt = 0) -> Signal

The output signal of the gate.

Returns:

  • Signal ( Signal ) –

    The output signal of the gate.

ShiftRight

Bases: ShiftGate, BaseModel

A SHIFT-RIGHT gate.

A SHIFT-RIGHT gate is a gate that returns its left input shifted right by the number on the right side.

Methods:

  • change_mutability

    Change the mutability status of this instance and optionally its ports.

  • evaluate

    Evaluates the gate's output signal based on its input signals.

  • all_connections

    Returns a dictionary mapping port names to their corresponding connection paths.

  • model_post_init

    Initializes the gate's ports and connections.

  • connect

    Add connections to the specified port of this instance.

  • disconnect

    Remove an existing connection from a specified port of this instance.

  • get_connection

    Retrieve the connection path associated with a specified port and bit index.

  • modify_connection

    Modify an existing connection within a specified port of this instance.

  • connect_modify

    Add a new connection or modify an existing one within the specified port of this instance.

  • tie_port

    Set a constant signal value for the specified port and bit index.

  • has_tied_ports

    Checks the ports of this instance whether any are tied to constant values.

  • has_tied_inputs

    Checks the input ports of this instance whether any are tied to constant values.

  • has_tied_outputs

    Checks the output ports of this instance whether any are tied to constant values.

  • update_signedness

    Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

  • split

    Performs a bit-wise split on this instance.

  • p2v

    Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

  • ps2v

    Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

  • set

    Sets the signal on a port.

  • get_result

    Returns the result of this gate's operation for given Signals s1 and s2.

  • signals_in

    The input signals of the gate.

  • signal_out

    The output signal of the gate.

Attributes:

name instance-attribute

name: str

The name of the element.

!!! Do not modify this variable after instantiating it. Use NetlistElement.set_name() instead. Modifying this variable might lead to inconsistencies later on.

metadata class-attribute instance-attribute

Metadata of a netlist element.

Can be user-defined, or e. g. by Yosys (such as src for the HDL source). Is also grouped by categories, i.e. all metadata from Yosys can be accessed via Module.metadata["yosys"], or via Module.metadata.yosys, which both return a dictionary of all metadata. Read the documentation of MetaDataMixin for more information.

path property

Returns the InstancePath of the netlist element.

The InstancePath object is constructed using the element's type and its raw hierarchical path.

Returns:

  • InstancePath ( InstancePath ) –

    The hierarchical path of the netlist element.

type property

type: EType

The type of the element, which is an instance.

hierarchy_level property

hierarchy_level: int

The level of hierarchy of the element in the design.

The hierarchy level is the number of separators in the element's raw path. For example, a top-level instance has a hierarchy level of 0, while a direct submodule instance has a hierarchy level of 1.

Returns:

  • int ( int ) –

    The hierarchy level of the element.

has_parent property

has_parent: bool

Whether this object has a parent.

circuit property

circuit: 'Circuit'

The circuit object to which this netlist element belongs to.

  • For a module, returns the circuit to which the module belongs.
  • For any other netlist element, recursively returns the circuit of the parent, which ultimately leads to a module, to which the netlist element belongs.

Raises:

  • ParentNotFoundError

    If a parent cannot be resolved somewhere in the hierarchical chain.

  • ObjectNotFoundError

    If for a module no circuit is set.

has_circuit property

has_circuit: bool

Whether this netlist element has a defined circuit it belongs to.

Tries to access self.circuit and returns whether the call was successful. Can be used instead of a try-except clause around the call to NetlistElement.circuit.

locked property

locked: bool

True if this NetlistElement instance is locked (i.e. it is currently structurally unchangeable), False if it is mutable.

Can be changed via NetlistElement.change_mutability(bool).

Immutability is used to prevent accidental changes to the design.

is_placeholder_instance property

is_placeholder_instance: bool

A placeholder represents an element that does not have a specific path.

True if this NetlistElement instance represents a placeholder, False otherwise.

can_carry_signal property

can_carry_signal: bool

Whether this exact object is able to receive, pass or hold signal values.

True for ports (as they drive or receive values) and wires (as they pass the signals from driver to load ports) as well as their respective segments. False for instances and modules.

connections property

connections: Dict[str, Dict[int, WireSegmentPath]]

A dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port. Elements with no connection (i.e. the path is None) are excluded. In case these are needed, use Instance.get_connections() instead.

Example

{ 'port1': {1: WireSegmentPath('path/to/element1'), 2: WireSegmentPath('path/to/element2')}, 'port2': {1: WireSegmentPath('path/to/element3')} }

connection_str_paths property

connection_str_paths: Dict[str, Dict[int, str]]

Returns a dictionary mapping port names to their corresponding connection paths as strings.

The keys are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are the raw string paths.

Example

{ 'port1': {0: 'path.to.element1', 1: 'path.to.element2'}, 'port2': {0: 'path.to.element3'} }

ports property

A dictionary mapping port names to their corresponding Port objects.

The keys of the dictionary are the names of the ports. The values are Port objects representing the ports.

Returns:

input_ports property

input_ports: Tuple[Port[Instance], Port[Instance]]

The input ports of the gate as a 2-tuple.

output_ports property

output_ports: Tuple[Port[Instance], ...]

Returns a tuple of output ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as outputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the output ports.

has_unconnected_port_segments property

has_unconnected_port_segments: bool

Returns True if the instance has at least one unconnected port segment.

signals property

signals: Dict[str, SignalArray]

A dictionary with all signals currently present on all ports of this instance.

is_blackbox property

is_blackbox: bool

Flag indicating whether the instance represents neither a primitive element nor a module instance.

If True, this instance does not have a module definition, and is also not a basic component (i.e. a primitive gate instance) from the internal gate library, such as a gate or flip-flop.

y_width property

y_width: PositiveInt

Width of the gate, based on a certain port's width, depending on the actual gate.

a_width property

a_width: PositiveInt

Width of the gate's A port.

b_width property

b_width: PositiveInt

Width of the gate's B port.

is_combinational property

is_combinational: bool

Whether instances of this gate are considered combinational gates.

True for combinational gates, such as AND gates or arithmetic gates. False for flip-flops and latches.

is_sequential property

is_sequential: bool

Whether instances of this gate are considered sequential gates.

False for combinational gates, such as AND gates or arithmetic gates. True for flip-flops and latches.

output_port property

output_port: Port[Instance]

The output port of the gate.

data_width property

data_width: int

The data width of this instance.

Defaults to the data width of the output port. Can be overwritten in extended classes.

In contrast to self.width, which is used for the creation and initialization, this property is linked to the data width of the output port. This property is useful when the data width of the output port can be changed.

a_signed property

a_signed: bool

The signedness of input port A.

b_signed property

b_signed: bool

The signedness of input port B.

truth_table property

truth_table: Dict[Tuple[Signal, Signal], Signal]

A simple truth table as a dictionary.

This dictionary contains the input-output mapping for unary gates that evaluate bitwise (e.g. AndGate, OrGate). Not implemented for arithmetic gates (e.g. Adder).

change_mutability

change_mutability(is_now_locked: bool, recursive: bool = False) -> Self

Change the mutability status of this instance and optionally its ports.

This method allows setting whether this instance can be modified or not. If recursive is set to True, it also applies the same mutability status to all ports of this instance.

Parameters:

  • is_now_locked

    (bool) –

    The new mutability status for this instance.

  • recursive

    (bool, default: False ) –

    Whether to apply the change recursively to its ports. Defaults to False.

evaluate

evaluate() -> None

Evaluates the gate's output signal based on its input signals.

This method is called when the gate's input signals change, and it updates the gate's output signal accordingly.

all_connections

all_connections(
    include_unconnected: bool,
) -> Dict[str, Dict[int, WireSegmentPath]]

Returns a dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port.

Parameters:

  • include_unconnected

    (bool) –

    Whether to include unconnected ports in the result.

Returns:

model_post_init

model_post_init(__context: object) -> None

Initializes the gate's ports and connections.

This method is called after the gate's attributes have been initialized, and it sets up the gate's ports and connections.

connect

connect(
    port_name: str,
    ws_path: Optional[WireSegmentPath],
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add connections to the specified port of this instance.

This method can establish multiple connections if a range of indices is provided.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection(s) should be established.

  • ws_path

    (Optional[WireSegmentPath]) –

    The path of the wire segment that will be connected to this port. If None, the associated port (segment) remains unconnected.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

Raises:

  • ObjectLockedError

    If this instance is currently locked, and no connection can be made.

disconnect

disconnect(port_name: str, index: Optional[int] = None) -> None

Remove an existing connection from a specified port of this instance.

This method disconnects the wire segment at the given index within the specified port_name.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be removed.

  • index

    (Optional[int], default: None ) –

    The bit index within the port for this disconnection. Defaults to None, which completely disconnects the port.

Raises:

get_connection

get_connection(
    port_name: str, index: Optional[NonNegativeInt] = None
) -> Union[WireSegmentPath, Dict[int, WireSegmentPath], None]

Retrieve the connection path associated with a specified port and bit index.

If index is provided, this method returns the wire segment path connected to that specific bit within the port. Otherwise, it returns all connections for the given port as a dictionary mapping indices to WireSegmentPaths.

Parameters:

  • port_name

    (str) –

    The name of the port for which to retrieve the connection(s).

  • index

    (Optional[NonNegativeInt], default: None ) –

    The bit index within the port. Defaults to None.

Returns:

modify_connection

modify_connection(
    port_name: str, ws_path: WireSegmentPath, index: NonNegativeInt = 0
) -> None

Modify an existing connection within a specified port of this instance.

This method updates the wire segment path at the given index within the specified port_name. If the index does not exist yet, it is newly added, changing the width of the port.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be modified.

  • ws_path

    (WireSegmentPath) –

    The new wire segment path for this connection.

  • index

    (NonNegativeInt, default: 0 ) –

    The bit index within the port. Defaults to 0.

connect_modify

connect_modify(
    port_name: str,
    ws_path: WireSegmentPath,
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add a new connection or modify an existing one within the specified port of this instance.

If the connection already exists at the given index and port_name, it will be modified. Otherwise, a new connection is added.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be established or updated.

  • ws_path

    (WireSegmentPath) –

    The path of the wire segment that will be connected to this port.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

tie_port

tie_port(name: str, index: NonNegativeInt, sig_value: LogicLevel) -> None

Set a constant signal value for the specified port and bit index.

If the specified port does not exist, an error message is logged and the function returns False. Otherwise, the method tries to set the constant signal value for that port and returns True if successful.

Does not work for instance output ports, as they are always driven by their parent instances.

Parameters:

  • name

    (str) –

    The name of the port.

  • index

    (NonNegativeInt) –

    The bit index within the port.

  • sig_value

    (LogicLevel) –

    The constant signal value to be set ('0', '1', or 'Z').

Raises:

  • ObjectNotFoundError

    If no such port or port segment exists.

  • AlreadyConnectedError

    (raised by: PortSegment.tie_signal) If this segment is belongs to a load port and is already connected to a wire, from which it receives its value.

  • InvalidDirectionError

    (raised by: PortSegment.tie_signal) If this port segment belongs to an instance output port, which is driven by the instance inputs and the instance's internal logic.

  • InvalidSignalError

    (raised by: PortSegment.tie_signal) If an invalid value is provided.

has_tied_ports

has_tied_ports() -> bool

Checks the ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any ports of this instance are tied to constant values. False otherwise, i.e. all ports are connected to wires.

has_tied_inputs

has_tied_inputs() -> bool

Checks the input ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any input ports of this instance are tied to constant values. False otherwise, i.e. all input ports are connected to wires.

has_tied_outputs

has_tied_outputs() -> bool

Checks the output ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any output ports of this instance are tied to constant values. False otherwise, i.e. all output ports are connected to wires.

update_signedness

update_signedness(port_name: str) -> None

Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

Parameters:

  • port_name

    (str) –

    The name of the port, of which the signedness value is retrieved.

split

split() -> Dict[NonNegativeInt, Self]

Performs a bit-wise split on this instance.

If this instance supports splitting and has a data width of n bit, this method splits this instance into n 1-bit instances. This works for instances, where each output bit depends only on the corresponding input bit(s), e.g. an AND gate or a D-Flipflop.

Returns:

  • Dict[NonNegativeInt, Self]

    Dict[int, Instance]: An n-bit large dictionary, where each key conforms to a bit of the original instance, and each value is an 1-bit instance representing the corresponding "slice" of the original instance.

Raises:

  • SplittingUnsupportedError

    If this instance does not support splitting. Happens for any gate or instance whose behavior depends on the whole bus, and splitting would make it lose its meaning.

p2v

p2v(
    port: ANY_PORT,
    exclude_indices: Optional[List[int]] = None,
    include_indices: Optional[List[int]] = None,
) -> str

Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a Port object and converts them to their corresponding Verilog signal structure (p2v -> Port to Verilog signal syntax). For each segment of the port, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port is set to a constant, the corresponding constant wire segment placeholder is used instead. Port segments can be excluded from the conversion by providing a list of indices to the exclude_indices parameter, indicating which segments should be excluded from the conversion (e.g. segments that are known to be unconnected). Vice versa, only a certain subset of the port's segments may be converted to Verilog syntax, if include_indices is a given list of port indices. All indices not present in the list will be excluded from the conversion.

Parameters:

  • port

    (Port) –

    The Port object to convert.

  • exclude_indices

    (List[int], default: None ) –

    A list of indices to exclude from the conversion. Defaults to None.

  • include_indices

    (List[int], default: None ) –

    A list of indices (i.e. port slices) to include only for the conversion. Defaults to None.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

  • ObjectNotFoundError

    If the wire connected to a certain port segment could not be found.

  • UnsupportedOperationError

    If both exclude_indices and include_indices are specified. Only one of both may be given when calling this method.

ps2v

Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a PortSegment dictionary and converts them to their corresponding Verilog signal structure (ps2v -> PortSegment to Verilog signal syntax). For each segment, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port segment is set to a constant, the corresponding constant wire segment placeholder is used instead.

Parameters:

  • ps_dict

    (Dict[int, PortSegment]) –

    The PortSegment dictionary to convert. Each key (int) conforms to the index of the associated PortSegment object.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

set

set(
    port_name: str,
    new_signal: SignalOrLogicLevel,
    idx: Union[int, List[int]] = 0,
) -> None

Sets the signal on a port.

Parameters:

  • port_name

    (str) –

    The name of the port to set the signal on.

  • new_signal

    (Signal) –

    The new signal value.

  • idx

    (Union[int, List[int]], default: 0 ) –

    The index (or indices) to apply the given signal to. Can either be an integer (single index to set) or an iterable of integers (e.g. a list of indices). For every integer of the iterable the signal value of the corresponding port index is set to the given new_signal. Defaults to 0.

Example

from netlist_carpentry.utils.gate_factory import and_gate module = Module(name='m') a = module.create_port('a', 'input', width=6) instance = and_gate(module, 'inst', A=a)

This sets the value of bit 0 of port A to HIGH

instance.set('A', 1, 0) instance.ports['A'].signal_str 'xxxxx1'

This sets the value of bits 1, 3 and 5 of port A to LOW, leaving the other bits as they already are.

instance.set('A', 0, [1, 3, 5]) instance.ports['A'].signal_str '0x0x01'

get_result

get_result(s1: Signal, s2: Signal) -> Signal

Returns the result of this gate's operation for given Signals s1 and s2.

This method is only implemented for bitwise evaluating gates (e.g. AndGate, OrGate). This method raises an UnsupportedOperationError if used on other gates (e.g. Adder).

For vector-level operations on full signal arrays, use :meth:get_result_vector instead.

Parameters:

  • s1

    (Signal) –

    The first Signal, i.e. the first operand.

  • s2

    (Signal) –

    The second Signal, i.e. the second operand.

Raises:

Returns:

  • Signal ( Signal ) –

    The result of this gate's operation on the given signals.

signals_in

signals_in(idx: NonNegativeInt = 0) -> Tuple[Signal, Signal]

The input signals of the gate.

Returns:

signal_out

signal_out(idx: NonNegativeInt = 0) -> Signal

The output signal of the gate.

Returns:

  • Signal ( Signal ) –

    The output signal of the gate.

ArithmeticShiftLeft

Bases: ShiftGate, BaseModel

An ARITHMETIC SHIFT-LEFT gate.

An ARITHMETIC SHIFT-LEFT gate is a gate that returns its left input shifted left by the number on the right side.

Methods:

  • change_mutability

    Change the mutability status of this instance and optionally its ports.

  • evaluate

    Evaluates the gate's output signal based on its input signals.

  • all_connections

    Returns a dictionary mapping port names to their corresponding connection paths.

  • model_post_init

    Initializes the gate's ports and connections.

  • connect

    Add connections to the specified port of this instance.

  • disconnect

    Remove an existing connection from a specified port of this instance.

  • get_connection

    Retrieve the connection path associated with a specified port and bit index.

  • modify_connection

    Modify an existing connection within a specified port of this instance.

  • connect_modify

    Add a new connection or modify an existing one within the specified port of this instance.

  • tie_port

    Set a constant signal value for the specified port and bit index.

  • has_tied_ports

    Checks the ports of this instance whether any are tied to constant values.

  • has_tied_inputs

    Checks the input ports of this instance whether any are tied to constant values.

  • has_tied_outputs

    Checks the output ports of this instance whether any are tied to constant values.

  • update_signedness

    Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

  • split

    Performs a bit-wise split on this instance.

  • p2v

    Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

  • ps2v

    Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

  • set

    Sets the signal on a port.

  • get_result

    Returns the result of this gate's operation for given Signals s1 and s2.

  • signals_in

    The input signals of the gate.

  • signal_out

    The output signal of the gate.

Attributes:

name instance-attribute

name: str

The name of the element.

!!! Do not modify this variable after instantiating it. Use NetlistElement.set_name() instead. Modifying this variable might lead to inconsistencies later on.

metadata class-attribute instance-attribute

Metadata of a netlist element.

Can be user-defined, or e. g. by Yosys (such as src for the HDL source). Is also grouped by categories, i.e. all metadata from Yosys can be accessed via Module.metadata["yosys"], or via Module.metadata.yosys, which both return a dictionary of all metadata. Read the documentation of MetaDataMixin for more information.

path property

Returns the InstancePath of the netlist element.

The InstancePath object is constructed using the element's type and its raw hierarchical path.

Returns:

  • InstancePath ( InstancePath ) –

    The hierarchical path of the netlist element.

type property

type: EType

The type of the element, which is an instance.

hierarchy_level property

hierarchy_level: int

The level of hierarchy of the element in the design.

The hierarchy level is the number of separators in the element's raw path. For example, a top-level instance has a hierarchy level of 0, while a direct submodule instance has a hierarchy level of 1.

Returns:

  • int ( int ) –

    The hierarchy level of the element.

has_parent property

has_parent: bool

Whether this object has a parent.

circuit property

circuit: 'Circuit'

The circuit object to which this netlist element belongs to.

  • For a module, returns the circuit to which the module belongs.
  • For any other netlist element, recursively returns the circuit of the parent, which ultimately leads to a module, to which the netlist element belongs.

Raises:

  • ParentNotFoundError

    If a parent cannot be resolved somewhere in the hierarchical chain.

  • ObjectNotFoundError

    If for a module no circuit is set.

has_circuit property

has_circuit: bool

Whether this netlist element has a defined circuit it belongs to.

Tries to access self.circuit and returns whether the call was successful. Can be used instead of a try-except clause around the call to NetlistElement.circuit.

locked property

locked: bool

True if this NetlistElement instance is locked (i.e. it is currently structurally unchangeable), False if it is mutable.

Can be changed via NetlistElement.change_mutability(bool).

Immutability is used to prevent accidental changes to the design.

is_placeholder_instance property

is_placeholder_instance: bool

A placeholder represents an element that does not have a specific path.

True if this NetlistElement instance represents a placeholder, False otherwise.

can_carry_signal property

can_carry_signal: bool

Whether this exact object is able to receive, pass or hold signal values.

True for ports (as they drive or receive values) and wires (as they pass the signals from driver to load ports) as well as their respective segments. False for instances and modules.

connections property

connections: Dict[str, Dict[int, WireSegmentPath]]

A dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port. Elements with no connection (i.e. the path is None) are excluded. In case these are needed, use Instance.get_connections() instead.

Example

{ 'port1': {1: WireSegmentPath('path/to/element1'), 2: WireSegmentPath('path/to/element2')}, 'port2': {1: WireSegmentPath('path/to/element3')} }

connection_str_paths property

connection_str_paths: Dict[str, Dict[int, str]]

Returns a dictionary mapping port names to their corresponding connection paths as strings.

The keys are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are the raw string paths.

Example

{ 'port1': {0: 'path.to.element1', 1: 'path.to.element2'}, 'port2': {0: 'path.to.element3'} }

ports property

A dictionary mapping port names to their corresponding Port objects.

The keys of the dictionary are the names of the ports. The values are Port objects representing the ports.

Returns:

input_ports property

input_ports: Tuple[Port[Instance], Port[Instance]]

The input ports of the gate as a 2-tuple.

output_ports property

output_ports: Tuple[Port[Instance], ...]

Returns a tuple of output ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as outputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the output ports.

has_unconnected_port_segments property

has_unconnected_port_segments: bool

Returns True if the instance has at least one unconnected port segment.

signals property

signals: Dict[str, SignalArray]

A dictionary with all signals currently present on all ports of this instance.

is_blackbox property

is_blackbox: bool

Flag indicating whether the instance represents neither a primitive element nor a module instance.

If True, this instance does not have a module definition, and is also not a basic component (i.e. a primitive gate instance) from the internal gate library, such as a gate or flip-flop.

y_width property

y_width: PositiveInt

Width of the gate, based on a certain port's width, depending on the actual gate.

a_width property

a_width: PositiveInt

Width of the gate's A port.

b_width property

b_width: PositiveInt

Width of the gate's B port.

is_combinational property

is_combinational: bool

Whether instances of this gate are considered combinational gates.

True for combinational gates, such as AND gates or arithmetic gates. False for flip-flops and latches.

is_sequential property

is_sequential: bool

Whether instances of this gate are considered sequential gates.

False for combinational gates, such as AND gates or arithmetic gates. True for flip-flops and latches.

output_port property

output_port: Port[Instance]

The output port of the gate.

data_width property

data_width: int

The data width of this instance.

Defaults to the data width of the output port. Can be overwritten in extended classes.

In contrast to self.width, which is used for the creation and initialization, this property is linked to the data width of the output port. This property is useful when the data width of the output port can be changed.

a_signed property

a_signed: bool

The signedness of input port A.

b_signed property

b_signed: bool

The signedness of input port B.

truth_table property

truth_table: Dict[Tuple[Signal, Signal], Signal]

A simple truth table as a dictionary.

This dictionary contains the input-output mapping for unary gates that evaluate bitwise (e.g. AndGate, OrGate). Not implemented for arithmetic gates (e.g. Adder).

change_mutability

change_mutability(is_now_locked: bool, recursive: bool = False) -> Self

Change the mutability status of this instance and optionally its ports.

This method allows setting whether this instance can be modified or not. If recursive is set to True, it also applies the same mutability status to all ports of this instance.

Parameters:

  • is_now_locked

    (bool) –

    The new mutability status for this instance.

  • recursive

    (bool, default: False ) –

    Whether to apply the change recursively to its ports. Defaults to False.

evaluate

evaluate() -> None

Evaluates the gate's output signal based on its input signals.

This method is called when the gate's input signals change, and it updates the gate's output signal accordingly.

all_connections

all_connections(
    include_unconnected: bool,
) -> Dict[str, Dict[int, WireSegmentPath]]

Returns a dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port.

Parameters:

  • include_unconnected

    (bool) –

    Whether to include unconnected ports in the result.

Returns:

model_post_init

model_post_init(__context: object) -> None

Initializes the gate's ports and connections.

This method is called after the gate's attributes have been initialized, and it sets up the gate's ports and connections.

connect

connect(
    port_name: str,
    ws_path: Optional[WireSegmentPath],
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add connections to the specified port of this instance.

This method can establish multiple connections if a range of indices is provided.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection(s) should be established.

  • ws_path

    (Optional[WireSegmentPath]) –

    The path of the wire segment that will be connected to this port. If None, the associated port (segment) remains unconnected.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

Raises:

  • ObjectLockedError

    If this instance is currently locked, and no connection can be made.

disconnect

disconnect(port_name: str, index: Optional[int] = None) -> None

Remove an existing connection from a specified port of this instance.

This method disconnects the wire segment at the given index within the specified port_name.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be removed.

  • index

    (Optional[int], default: None ) –

    The bit index within the port for this disconnection. Defaults to None, which completely disconnects the port.

Raises:

get_connection

get_connection(
    port_name: str, index: Optional[NonNegativeInt] = None
) -> Union[WireSegmentPath, Dict[int, WireSegmentPath], None]

Retrieve the connection path associated with a specified port and bit index.

If index is provided, this method returns the wire segment path connected to that specific bit within the port. Otherwise, it returns all connections for the given port as a dictionary mapping indices to WireSegmentPaths.

Parameters:

  • port_name

    (str) –

    The name of the port for which to retrieve the connection(s).

  • index

    (Optional[NonNegativeInt], default: None ) –

    The bit index within the port. Defaults to None.

Returns:

modify_connection

modify_connection(
    port_name: str, ws_path: WireSegmentPath, index: NonNegativeInt = 0
) -> None

Modify an existing connection within a specified port of this instance.

This method updates the wire segment path at the given index within the specified port_name. If the index does not exist yet, it is newly added, changing the width of the port.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be modified.

  • ws_path

    (WireSegmentPath) –

    The new wire segment path for this connection.

  • index

    (NonNegativeInt, default: 0 ) –

    The bit index within the port. Defaults to 0.

connect_modify

connect_modify(
    port_name: str,
    ws_path: WireSegmentPath,
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add a new connection or modify an existing one within the specified port of this instance.

If the connection already exists at the given index and port_name, it will be modified. Otherwise, a new connection is added.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be established or updated.

  • ws_path

    (WireSegmentPath) –

    The path of the wire segment that will be connected to this port.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

tie_port

tie_port(name: str, index: NonNegativeInt, sig_value: LogicLevel) -> None

Set a constant signal value for the specified port and bit index.

If the specified port does not exist, an error message is logged and the function returns False. Otherwise, the method tries to set the constant signal value for that port and returns True if successful.

Does not work for instance output ports, as they are always driven by their parent instances.

Parameters:

  • name

    (str) –

    The name of the port.

  • index

    (NonNegativeInt) –

    The bit index within the port.

  • sig_value

    (LogicLevel) –

    The constant signal value to be set ('0', '1', or 'Z').

Raises:

  • ObjectNotFoundError

    If no such port or port segment exists.

  • AlreadyConnectedError

    (raised by: PortSegment.tie_signal) If this segment is belongs to a load port and is already connected to a wire, from which it receives its value.

  • InvalidDirectionError

    (raised by: PortSegment.tie_signal) If this port segment belongs to an instance output port, which is driven by the instance inputs and the instance's internal logic.

  • InvalidSignalError

    (raised by: PortSegment.tie_signal) If an invalid value is provided.

has_tied_ports

has_tied_ports() -> bool

Checks the ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any ports of this instance are tied to constant values. False otherwise, i.e. all ports are connected to wires.

has_tied_inputs

has_tied_inputs() -> bool

Checks the input ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any input ports of this instance are tied to constant values. False otherwise, i.e. all input ports are connected to wires.

has_tied_outputs

has_tied_outputs() -> bool

Checks the output ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any output ports of this instance are tied to constant values. False otherwise, i.e. all output ports are connected to wires.

update_signedness

update_signedness(port_name: str) -> None

Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

Parameters:

  • port_name

    (str) –

    The name of the port, of which the signedness value is retrieved.

split

split() -> Dict[NonNegativeInt, Self]

Performs a bit-wise split on this instance.

If this instance supports splitting and has a data width of n bit, this method splits this instance into n 1-bit instances. This works for instances, where each output bit depends only on the corresponding input bit(s), e.g. an AND gate or a D-Flipflop.

Returns:

  • Dict[NonNegativeInt, Self]

    Dict[int, Instance]: An n-bit large dictionary, where each key conforms to a bit of the original instance, and each value is an 1-bit instance representing the corresponding "slice" of the original instance.

Raises:

  • SplittingUnsupportedError

    If this instance does not support splitting. Happens for any gate or instance whose behavior depends on the whole bus, and splitting would make it lose its meaning.

p2v

p2v(
    port: ANY_PORT,
    exclude_indices: Optional[List[int]] = None,
    include_indices: Optional[List[int]] = None,
) -> str

Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a Port object and converts them to their corresponding Verilog signal structure (p2v -> Port to Verilog signal syntax). For each segment of the port, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port is set to a constant, the corresponding constant wire segment placeholder is used instead. Port segments can be excluded from the conversion by providing a list of indices to the exclude_indices parameter, indicating which segments should be excluded from the conversion (e.g. segments that are known to be unconnected). Vice versa, only a certain subset of the port's segments may be converted to Verilog syntax, if include_indices is a given list of port indices. All indices not present in the list will be excluded from the conversion.

Parameters:

  • port

    (Port) –

    The Port object to convert.

  • exclude_indices

    (List[int], default: None ) –

    A list of indices to exclude from the conversion. Defaults to None.

  • include_indices

    (List[int], default: None ) –

    A list of indices (i.e. port slices) to include only for the conversion. Defaults to None.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

  • ObjectNotFoundError

    If the wire connected to a certain port segment could not be found.

  • UnsupportedOperationError

    If both exclude_indices and include_indices are specified. Only one of both may be given when calling this method.

ps2v

Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a PortSegment dictionary and converts them to their corresponding Verilog signal structure (ps2v -> PortSegment to Verilog signal syntax). For each segment, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port segment is set to a constant, the corresponding constant wire segment placeholder is used instead.

Parameters:

  • ps_dict

    (Dict[int, PortSegment]) –

    The PortSegment dictionary to convert. Each key (int) conforms to the index of the associated PortSegment object.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

set

set(
    port_name: str,
    new_signal: SignalOrLogicLevel,
    idx: Union[int, List[int]] = 0,
) -> None

Sets the signal on a port.

Parameters:

  • port_name

    (str) –

    The name of the port to set the signal on.

  • new_signal

    (Signal) –

    The new signal value.

  • idx

    (Union[int, List[int]], default: 0 ) –

    The index (or indices) to apply the given signal to. Can either be an integer (single index to set) or an iterable of integers (e.g. a list of indices). For every integer of the iterable the signal value of the corresponding port index is set to the given new_signal. Defaults to 0.

Example

from netlist_carpentry.utils.gate_factory import and_gate module = Module(name='m') a = module.create_port('a', 'input', width=6) instance = and_gate(module, 'inst', A=a)

This sets the value of bit 0 of port A to HIGH

instance.set('A', 1, 0) instance.ports['A'].signal_str 'xxxxx1'

This sets the value of bits 1, 3 and 5 of port A to LOW, leaving the other bits as they already are.

instance.set('A', 0, [1, 3, 5]) instance.ports['A'].signal_str '0x0x01'

get_result

get_result(s1: Signal, s2: Signal) -> Signal

Returns the result of this gate's operation for given Signals s1 and s2.

This method is only implemented for bitwise evaluating gates (e.g. AndGate, OrGate). This method raises an UnsupportedOperationError if used on other gates (e.g. Adder).

For vector-level operations on full signal arrays, use :meth:get_result_vector instead.

Parameters:

  • s1

    (Signal) –

    The first Signal, i.e. the first operand.

  • s2

    (Signal) –

    The second Signal, i.e. the second operand.

Raises:

Returns:

  • Signal ( Signal ) –

    The result of this gate's operation on the given signals.

signals_in

signals_in(idx: NonNegativeInt = 0) -> Tuple[Signal, Signal]

The input signals of the gate.

Returns:

signal_out

signal_out(idx: NonNegativeInt = 0) -> Signal

The output signal of the gate.

Returns:

  • Signal ( Signal ) –

    The output signal of the gate.

ArithmeticShiftRight

Bases: ShiftGate, BaseModel

An ARITHMETIC SHIFT-RIGHT gate.

An ARITHMETIC SHIFT-RIGHT gate is a gate that returns its left input shifted right by the number on the right side.

Methods:

  • change_mutability

    Change the mutability status of this instance and optionally its ports.

  • evaluate

    Evaluates the gate's output signal based on its input signals.

  • all_connections

    Returns a dictionary mapping port names to their corresponding connection paths.

  • model_post_init

    Initializes the gate's ports and connections.

  • connect

    Add connections to the specified port of this instance.

  • disconnect

    Remove an existing connection from a specified port of this instance.

  • get_connection

    Retrieve the connection path associated with a specified port and bit index.

  • modify_connection

    Modify an existing connection within a specified port of this instance.

  • connect_modify

    Add a new connection or modify an existing one within the specified port of this instance.

  • tie_port

    Set a constant signal value for the specified port and bit index.

  • has_tied_ports

    Checks the ports of this instance whether any are tied to constant values.

  • has_tied_inputs

    Checks the input ports of this instance whether any are tied to constant values.

  • has_tied_outputs

    Checks the output ports of this instance whether any are tied to constant values.

  • update_signedness

    Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

  • split

    Performs a bit-wise split on this instance.

  • p2v

    Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

  • ps2v

    Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

  • set

    Sets the signal on a port.

  • get_result

    Returns the result of this gate's operation for given Signals s1 and s2.

  • signals_in

    The input signals of the gate.

  • signal_out

    The output signal of the gate.

Attributes:

name instance-attribute

name: str

The name of the element.

!!! Do not modify this variable after instantiating it. Use NetlistElement.set_name() instead. Modifying this variable might lead to inconsistencies later on.

metadata class-attribute instance-attribute

Metadata of a netlist element.

Can be user-defined, or e. g. by Yosys (such as src for the HDL source). Is also grouped by categories, i.e. all metadata from Yosys can be accessed via Module.metadata["yosys"], or via Module.metadata.yosys, which both return a dictionary of all metadata. Read the documentation of MetaDataMixin for more information.

path property

Returns the InstancePath of the netlist element.

The InstancePath object is constructed using the element's type and its raw hierarchical path.

Returns:

  • InstancePath ( InstancePath ) –

    The hierarchical path of the netlist element.

type property

type: EType

The type of the element, which is an instance.

hierarchy_level property

hierarchy_level: int

The level of hierarchy of the element in the design.

The hierarchy level is the number of separators in the element's raw path. For example, a top-level instance has a hierarchy level of 0, while a direct submodule instance has a hierarchy level of 1.

Returns:

  • int ( int ) –

    The hierarchy level of the element.

has_parent property

has_parent: bool

Whether this object has a parent.

circuit property

circuit: 'Circuit'

The circuit object to which this netlist element belongs to.

  • For a module, returns the circuit to which the module belongs.
  • For any other netlist element, recursively returns the circuit of the parent, which ultimately leads to a module, to which the netlist element belongs.

Raises:

  • ParentNotFoundError

    If a parent cannot be resolved somewhere in the hierarchical chain.

  • ObjectNotFoundError

    If for a module no circuit is set.

has_circuit property

has_circuit: bool

Whether this netlist element has a defined circuit it belongs to.

Tries to access self.circuit and returns whether the call was successful. Can be used instead of a try-except clause around the call to NetlistElement.circuit.

locked property

locked: bool

True if this NetlistElement instance is locked (i.e. it is currently structurally unchangeable), False if it is mutable.

Can be changed via NetlistElement.change_mutability(bool).

Immutability is used to prevent accidental changes to the design.

is_placeholder_instance property

is_placeholder_instance: bool

A placeholder represents an element that does not have a specific path.

True if this NetlistElement instance represents a placeholder, False otherwise.

can_carry_signal property

can_carry_signal: bool

Whether this exact object is able to receive, pass or hold signal values.

True for ports (as they drive or receive values) and wires (as they pass the signals from driver to load ports) as well as their respective segments. False for instances and modules.

connections property

connections: Dict[str, Dict[int, WireSegmentPath]]

A dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port. Elements with no connection (i.e. the path is None) are excluded. In case these are needed, use Instance.get_connections() instead.

Example

{ 'port1': {1: WireSegmentPath('path/to/element1'), 2: WireSegmentPath('path/to/element2')}, 'port2': {1: WireSegmentPath('path/to/element3')} }

connection_str_paths property

connection_str_paths: Dict[str, Dict[int, str]]

Returns a dictionary mapping port names to their corresponding connection paths as strings.

The keys are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are the raw string paths.

Example

{ 'port1': {0: 'path.to.element1', 1: 'path.to.element2'}, 'port2': {0: 'path.to.element3'} }

ports property

A dictionary mapping port names to their corresponding Port objects.

The keys of the dictionary are the names of the ports. The values are Port objects representing the ports.

Returns:

input_ports property

input_ports: Tuple[Port[Instance], Port[Instance]]

The input ports of the gate as a 2-tuple.

output_ports property

output_ports: Tuple[Port[Instance], ...]

Returns a tuple of output ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as outputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the output ports.

has_unconnected_port_segments property

has_unconnected_port_segments: bool

Returns True if the instance has at least one unconnected port segment.

signals property

signals: Dict[str, SignalArray]

A dictionary with all signals currently present on all ports of this instance.

is_blackbox property

is_blackbox: bool

Flag indicating whether the instance represents neither a primitive element nor a module instance.

If True, this instance does not have a module definition, and is also not a basic component (i.e. a primitive gate instance) from the internal gate library, such as a gate or flip-flop.

y_width property

y_width: PositiveInt

Width of the gate, based on a certain port's width, depending on the actual gate.

a_width property

a_width: PositiveInt

Width of the gate's A port.

b_width property

b_width: PositiveInt

Width of the gate's B port.

is_combinational property

is_combinational: bool

Whether instances of this gate are considered combinational gates.

True for combinational gates, such as AND gates or arithmetic gates. False for flip-flops and latches.

is_sequential property

is_sequential: bool

Whether instances of this gate are considered sequential gates.

False for combinational gates, such as AND gates or arithmetic gates. True for flip-flops and latches.

output_port property

output_port: Port[Instance]

The output port of the gate.

data_width property

data_width: int

The data width of this instance.

Defaults to the data width of the output port. Can be overwritten in extended classes.

In contrast to self.width, which is used for the creation and initialization, this property is linked to the data width of the output port. This property is useful when the data width of the output port can be changed.

a_signed property

a_signed: bool

The signedness of input port A.

b_signed property

b_signed: bool

The signedness of input port B.

truth_table property

truth_table: Dict[Tuple[Signal, Signal], Signal]

A simple truth table as a dictionary.

This dictionary contains the input-output mapping for unary gates that evaluate bitwise (e.g. AndGate, OrGate). Not implemented for arithmetic gates (e.g. Adder).

change_mutability

change_mutability(is_now_locked: bool, recursive: bool = False) -> Self

Change the mutability status of this instance and optionally its ports.

This method allows setting whether this instance can be modified or not. If recursive is set to True, it also applies the same mutability status to all ports of this instance.

Parameters:

  • is_now_locked

    (bool) –

    The new mutability status for this instance.

  • recursive

    (bool, default: False ) –

    Whether to apply the change recursively to its ports. Defaults to False.

evaluate

evaluate() -> None

Evaluates the gate's output signal based on its input signals.

This method is called when the gate's input signals change, and it updates the gate's output signal accordingly.

all_connections

all_connections(
    include_unconnected: bool,
) -> Dict[str, Dict[int, WireSegmentPath]]

Returns a dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port.

Parameters:

  • include_unconnected

    (bool) –

    Whether to include unconnected ports in the result.

Returns:

model_post_init

model_post_init(__context: object) -> None

Initializes the gate's ports and connections.

This method is called after the gate's attributes have been initialized, and it sets up the gate's ports and connections.

connect

connect(
    port_name: str,
    ws_path: Optional[WireSegmentPath],
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add connections to the specified port of this instance.

This method can establish multiple connections if a range of indices is provided.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection(s) should be established.

  • ws_path

    (Optional[WireSegmentPath]) –

    The path of the wire segment that will be connected to this port. If None, the associated port (segment) remains unconnected.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

Raises:

  • ObjectLockedError

    If this instance is currently locked, and no connection can be made.

disconnect

disconnect(port_name: str, index: Optional[int] = None) -> None

Remove an existing connection from a specified port of this instance.

This method disconnects the wire segment at the given index within the specified port_name.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be removed.

  • index

    (Optional[int], default: None ) –

    The bit index within the port for this disconnection. Defaults to None, which completely disconnects the port.

Raises:

get_connection

get_connection(
    port_name: str, index: Optional[NonNegativeInt] = None
) -> Union[WireSegmentPath, Dict[int, WireSegmentPath], None]

Retrieve the connection path associated with a specified port and bit index.

If index is provided, this method returns the wire segment path connected to that specific bit within the port. Otherwise, it returns all connections for the given port as a dictionary mapping indices to WireSegmentPaths.

Parameters:

  • port_name

    (str) –

    The name of the port for which to retrieve the connection(s).

  • index

    (Optional[NonNegativeInt], default: None ) –

    The bit index within the port. Defaults to None.

Returns:

modify_connection

modify_connection(
    port_name: str, ws_path: WireSegmentPath, index: NonNegativeInt = 0
) -> None

Modify an existing connection within a specified port of this instance.

This method updates the wire segment path at the given index within the specified port_name. If the index does not exist yet, it is newly added, changing the width of the port.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be modified.

  • ws_path

    (WireSegmentPath) –

    The new wire segment path for this connection.

  • index

    (NonNegativeInt, default: 0 ) –

    The bit index within the port. Defaults to 0.

connect_modify

connect_modify(
    port_name: str,
    ws_path: WireSegmentPath,
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add a new connection or modify an existing one within the specified port of this instance.

If the connection already exists at the given index and port_name, it will be modified. Otherwise, a new connection is added.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be established or updated.

  • ws_path

    (WireSegmentPath) –

    The path of the wire segment that will be connected to this port.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

tie_port

tie_port(name: str, index: NonNegativeInt, sig_value: LogicLevel) -> None

Set a constant signal value for the specified port and bit index.

If the specified port does not exist, an error message is logged and the function returns False. Otherwise, the method tries to set the constant signal value for that port and returns True if successful.

Does not work for instance output ports, as they are always driven by their parent instances.

Parameters:

  • name

    (str) –

    The name of the port.

  • index

    (NonNegativeInt) –

    The bit index within the port.

  • sig_value

    (LogicLevel) –

    The constant signal value to be set ('0', '1', or 'Z').

Raises:

  • ObjectNotFoundError

    If no such port or port segment exists.

  • AlreadyConnectedError

    (raised by: PortSegment.tie_signal) If this segment is belongs to a load port and is already connected to a wire, from which it receives its value.

  • InvalidDirectionError

    (raised by: PortSegment.tie_signal) If this port segment belongs to an instance output port, which is driven by the instance inputs and the instance's internal logic.

  • InvalidSignalError

    (raised by: PortSegment.tie_signal) If an invalid value is provided.

has_tied_ports

has_tied_ports() -> bool

Checks the ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any ports of this instance are tied to constant values. False otherwise, i.e. all ports are connected to wires.

has_tied_inputs

has_tied_inputs() -> bool

Checks the input ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any input ports of this instance are tied to constant values. False otherwise, i.e. all input ports are connected to wires.

has_tied_outputs

has_tied_outputs() -> bool

Checks the output ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any output ports of this instance are tied to constant values. False otherwise, i.e. all output ports are connected to wires.

update_signedness

update_signedness(port_name: str) -> None

Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

Parameters:

  • port_name

    (str) –

    The name of the port, of which the signedness value is retrieved.

split

split() -> Dict[NonNegativeInt, Self]

Performs a bit-wise split on this instance.

If this instance supports splitting and has a data width of n bit, this method splits this instance into n 1-bit instances. This works for instances, where each output bit depends only on the corresponding input bit(s), e.g. an AND gate or a D-Flipflop.

Returns:

  • Dict[NonNegativeInt, Self]

    Dict[int, Instance]: An n-bit large dictionary, where each key conforms to a bit of the original instance, and each value is an 1-bit instance representing the corresponding "slice" of the original instance.

Raises:

  • SplittingUnsupportedError

    If this instance does not support splitting. Happens for any gate or instance whose behavior depends on the whole bus, and splitting would make it lose its meaning.

p2v

p2v(
    port: ANY_PORT,
    exclude_indices: Optional[List[int]] = None,
    include_indices: Optional[List[int]] = None,
) -> str

Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a Port object and converts them to their corresponding Verilog signal structure (p2v -> Port to Verilog signal syntax). For each segment of the port, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port is set to a constant, the corresponding constant wire segment placeholder is used instead. Port segments can be excluded from the conversion by providing a list of indices to the exclude_indices parameter, indicating which segments should be excluded from the conversion (e.g. segments that are known to be unconnected). Vice versa, only a certain subset of the port's segments may be converted to Verilog syntax, if include_indices is a given list of port indices. All indices not present in the list will be excluded from the conversion.

Parameters:

  • port

    (Port) –

    The Port object to convert.

  • exclude_indices

    (List[int], default: None ) –

    A list of indices to exclude from the conversion. Defaults to None.

  • include_indices

    (List[int], default: None ) –

    A list of indices (i.e. port slices) to include only for the conversion. Defaults to None.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

  • ObjectNotFoundError

    If the wire connected to a certain port segment could not be found.

  • UnsupportedOperationError

    If both exclude_indices and include_indices are specified. Only one of both may be given when calling this method.

ps2v

Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a PortSegment dictionary and converts them to their corresponding Verilog signal structure (ps2v -> PortSegment to Verilog signal syntax). For each segment, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port segment is set to a constant, the corresponding constant wire segment placeholder is used instead.

Parameters:

  • ps_dict

    (Dict[int, PortSegment]) –

    The PortSegment dictionary to convert. Each key (int) conforms to the index of the associated PortSegment object.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

set

set(
    port_name: str,
    new_signal: SignalOrLogicLevel,
    idx: Union[int, List[int]] = 0,
) -> None

Sets the signal on a port.

Parameters:

  • port_name

    (str) –

    The name of the port to set the signal on.

  • new_signal

    (Signal) –

    The new signal value.

  • idx

    (Union[int, List[int]], default: 0 ) –

    The index (or indices) to apply the given signal to. Can either be an integer (single index to set) or an iterable of integers (e.g. a list of indices). For every integer of the iterable the signal value of the corresponding port index is set to the given new_signal. Defaults to 0.

Example

from netlist_carpentry.utils.gate_factory import and_gate module = Module(name='m') a = module.create_port('a', 'input', width=6) instance = and_gate(module, 'inst', A=a)

This sets the value of bit 0 of port A to HIGH

instance.set('A', 1, 0) instance.ports['A'].signal_str 'xxxxx1'

This sets the value of bits 1, 3 and 5 of port A to LOW, leaving the other bits as they already are.

instance.set('A', 0, [1, 3, 5]) instance.ports['A'].signal_str '0x0x01'

get_result

get_result(s1: Signal, s2: Signal) -> Signal

Returns the result of this gate's operation for given Signals s1 and s2.

This method is only implemented for bitwise evaluating gates (e.g. AndGate, OrGate). This method raises an UnsupportedOperationError if used on other gates (e.g. Adder).

For vector-level operations on full signal arrays, use :meth:get_result_vector instead.

Parameters:

  • s1

    (Signal) –

    The first Signal, i.e. the first operand.

  • s2

    (Signal) –

    The second Signal, i.e. the second operand.

Raises:

Returns:

  • Signal ( Signal ) –

    The result of this gate's operation on the given signals.

signals_in

signals_in(idx: NonNegativeInt = 0) -> Tuple[Signal, Signal]

The input signals of the gate.

Returns:

signal_out

signal_out(idx: NonNegativeInt = 0) -> Signal

The output signal of the gate.

Returns:

  • Signal ( Signal ) –

    The output signal of the gate.

ShiftX

Bases: ShiftGate, BaseModel

A SHIFT-X gate.

A SHIFT-X gate is a gate that returns its first input shifted right or left by the number on the second input, based on whether the second input is signed and negative or not.

Methods:

  • model_post_init

    Initializes the gate's ports and connections.

  • change_mutability

    Change the mutability status of this instance and optionally its ports.

  • evaluate

    Evaluates the gate's output signal based on its input signals.

  • all_connections

    Returns a dictionary mapping port names to their corresponding connection paths.

  • connect

    Add connections to the specified port of this instance.

  • disconnect

    Remove an existing connection from a specified port of this instance.

  • get_connection

    Retrieve the connection path associated with a specified port and bit index.

  • modify_connection

    Modify an existing connection within a specified port of this instance.

  • connect_modify

    Add a new connection or modify an existing one within the specified port of this instance.

  • tie_port

    Set a constant signal value for the specified port and bit index.

  • has_tied_ports

    Checks the ports of this instance whether any are tied to constant values.

  • has_tied_inputs

    Checks the input ports of this instance whether any are tied to constant values.

  • has_tied_outputs

    Checks the output ports of this instance whether any are tied to constant values.

  • update_signedness

    Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

  • split

    Performs a bit-wise split on this instance.

  • p2v

    Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

  • ps2v

    Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

  • set

    Sets the signal on a port.

  • get_result

    Returns the result of this gate's operation for given Signals s1 and s2.

  • get_result_vector

    Returns the result of this gate's operation for full signal vectors.

  • signals_in

    The input signals of the gate.

  • signal_out

    The output signal of the gate.

Attributes:

name instance-attribute

name: str

The name of the element.

!!! Do not modify this variable after instantiating it. Use NetlistElement.set_name() instead. Modifying this variable might lead to inconsistencies later on.

metadata class-attribute instance-attribute

Metadata of a netlist element.

Can be user-defined, or e. g. by Yosys (such as src for the HDL source). Is also grouped by categories, i.e. all metadata from Yosys can be accessed via Module.metadata["yosys"], or via Module.metadata.yosys, which both return a dictionary of all metadata. Read the documentation of MetaDataMixin for more information.

path property

Returns the InstancePath of the netlist element.

The InstancePath object is constructed using the element's type and its raw hierarchical path.

Returns:

  • InstancePath ( InstancePath ) –

    The hierarchical path of the netlist element.

type property

type: EType

The type of the element, which is an instance.

hierarchy_level property

hierarchy_level: int

The level of hierarchy of the element in the design.

The hierarchy level is the number of separators in the element's raw path. For example, a top-level instance has a hierarchy level of 0, while a direct submodule instance has a hierarchy level of 1.

Returns:

  • int ( int ) –

    The hierarchy level of the element.

has_parent property

has_parent: bool

Whether this object has a parent.

circuit property

circuit: 'Circuit'

The circuit object to which this netlist element belongs to.

  • For a module, returns the circuit to which the module belongs.
  • For any other netlist element, recursively returns the circuit of the parent, which ultimately leads to a module, to which the netlist element belongs.

Raises:

  • ParentNotFoundError

    If a parent cannot be resolved somewhere in the hierarchical chain.

  • ObjectNotFoundError

    If for a module no circuit is set.

has_circuit property

has_circuit: bool

Whether this netlist element has a defined circuit it belongs to.

Tries to access self.circuit and returns whether the call was successful. Can be used instead of a try-except clause around the call to NetlistElement.circuit.

locked property

locked: bool

True if this NetlistElement instance is locked (i.e. it is currently structurally unchangeable), False if it is mutable.

Can be changed via NetlistElement.change_mutability(bool).

Immutability is used to prevent accidental changes to the design.

is_placeholder_instance property

is_placeholder_instance: bool

A placeholder represents an element that does not have a specific path.

True if this NetlistElement instance represents a placeholder, False otherwise.

can_carry_signal property

can_carry_signal: bool

Whether this exact object is able to receive, pass or hold signal values.

True for ports (as they drive or receive values) and wires (as they pass the signals from driver to load ports) as well as their respective segments. False for instances and modules.

connections property

connections: Dict[str, Dict[int, WireSegmentPath]]

A dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port. Elements with no connection (i.e. the path is None) are excluded. In case these are needed, use Instance.get_connections() instead.

Example

{ 'port1': {1: WireSegmentPath('path/to/element1'), 2: WireSegmentPath('path/to/element2')}, 'port2': {1: WireSegmentPath('path/to/element3')} }

connection_str_paths property

connection_str_paths: Dict[str, Dict[int, str]]

Returns a dictionary mapping port names to their corresponding connection paths as strings.

The keys are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are the raw string paths.

Example

{ 'port1': {0: 'path.to.element1', 1: 'path.to.element2'}, 'port2': {0: 'path.to.element3'} }

ports property

A dictionary mapping port names to their corresponding Port objects.

The keys of the dictionary are the names of the ports. The values are Port objects representing the ports.

Returns:

input_ports property

input_ports: Tuple[Port[Instance], Port[Instance]]

The input ports of the gate as a 2-tuple.

output_ports property

output_ports: Tuple[Port[Instance], ...]

Returns a tuple of output ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as outputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the output ports.

has_unconnected_port_segments property

has_unconnected_port_segments: bool

Returns True if the instance has at least one unconnected port segment.

signals property

signals: Dict[str, SignalArray]

A dictionary with all signals currently present on all ports of this instance.

is_blackbox property

is_blackbox: bool

Flag indicating whether the instance represents neither a primitive element nor a module instance.

If True, this instance does not have a module definition, and is also not a basic component (i.e. a primitive gate instance) from the internal gate library, such as a gate or flip-flop.

y_width property

y_width: PositiveInt

Width of the gate, based on a certain port's width, depending on the actual gate.

a_width property

a_width: PositiveInt

Width of the gate's A port.

b_width property

b_width: PositiveInt

Width of the gate's B port.

is_combinational property

is_combinational: bool

Whether instances of this gate are considered combinational gates.

True for combinational gates, such as AND gates or arithmetic gates. False for flip-flops and latches.

is_sequential property

is_sequential: bool

Whether instances of this gate are considered sequential gates.

False for combinational gates, such as AND gates or arithmetic gates. True for flip-flops and latches.

output_port property

output_port: Port[Instance]

The output port of the gate.

data_width property

data_width: int

The data width of this instance.

Defaults to the data width of the output port. Can be overwritten in extended classes.

In contrast to self.width, which is used for the creation and initialization, this property is linked to the data width of the output port. This property is useful when the data width of the output port can be changed.

a_signed property

a_signed: bool

The signedness of input port A.

b_signed property

b_signed: bool

The signedness of input port B.

truth_table property

truth_table: Dict[Tuple[Signal, Signal], Signal]

A simple truth table as a dictionary.

This dictionary contains the input-output mapping for unary gates that evaluate bitwise (e.g. AndGate, OrGate). Not implemented for arithmetic gates (e.g. Adder).

model_post_init

model_post_init(__context: object) -> None

Initializes the gate's ports and connections.

This method is called after the gate's attributes have been initialized, and it sets up the gate's ports and connections.

change_mutability

change_mutability(is_now_locked: bool, recursive: bool = False) -> Self

Change the mutability status of this instance and optionally its ports.

This method allows setting whether this instance can be modified or not. If recursive is set to True, it also applies the same mutability status to all ports of this instance.

Parameters:

  • is_now_locked

    (bool) –

    The new mutability status for this instance.

  • recursive

    (bool, default: False ) –

    Whether to apply the change recursively to its ports. Defaults to False.

evaluate

evaluate() -> None

Evaluates the gate's output signal based on its input signals.

This method is called when the gate's input signals change, and it updates the gate's output signal accordingly.

all_connections

all_connections(
    include_unconnected: bool,
) -> Dict[str, Dict[int, WireSegmentPath]]

Returns a dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port.

Parameters:

  • include_unconnected

    (bool) –

    Whether to include unconnected ports in the result.

Returns:

connect

connect(
    port_name: str,
    ws_path: Optional[WireSegmentPath],
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add connections to the specified port of this instance.

This method can establish multiple connections if a range of indices is provided.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection(s) should be established.

  • ws_path

    (Optional[WireSegmentPath]) –

    The path of the wire segment that will be connected to this port. If None, the associated port (segment) remains unconnected.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

Raises:

  • ObjectLockedError

    If this instance is currently locked, and no connection can be made.

disconnect

disconnect(port_name: str, index: Optional[int] = None) -> None

Remove an existing connection from a specified port of this instance.

This method disconnects the wire segment at the given index within the specified port_name.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be removed.

  • index

    (Optional[int], default: None ) –

    The bit index within the port for this disconnection. Defaults to None, which completely disconnects the port.

Raises:

get_connection

get_connection(
    port_name: str, index: Optional[NonNegativeInt] = None
) -> Union[WireSegmentPath, Dict[int, WireSegmentPath], None]

Retrieve the connection path associated with a specified port and bit index.

If index is provided, this method returns the wire segment path connected to that specific bit within the port. Otherwise, it returns all connections for the given port as a dictionary mapping indices to WireSegmentPaths.

Parameters:

  • port_name

    (str) –

    The name of the port for which to retrieve the connection(s).

  • index

    (Optional[NonNegativeInt], default: None ) –

    The bit index within the port. Defaults to None.

Returns:

modify_connection

modify_connection(
    port_name: str, ws_path: WireSegmentPath, index: NonNegativeInt = 0
) -> None

Modify an existing connection within a specified port of this instance.

This method updates the wire segment path at the given index within the specified port_name. If the index does not exist yet, it is newly added, changing the width of the port.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be modified.

  • ws_path

    (WireSegmentPath) –

    The new wire segment path for this connection.

  • index

    (NonNegativeInt, default: 0 ) –

    The bit index within the port. Defaults to 0.

connect_modify

connect_modify(
    port_name: str,
    ws_path: WireSegmentPath,
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add a new connection or modify an existing one within the specified port of this instance.

If the connection already exists at the given index and port_name, it will be modified. Otherwise, a new connection is added.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be established or updated.

  • ws_path

    (WireSegmentPath) –

    The path of the wire segment that will be connected to this port.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

tie_port

tie_port(name: str, index: NonNegativeInt, sig_value: LogicLevel) -> None

Set a constant signal value for the specified port and bit index.

If the specified port does not exist, an error message is logged and the function returns False. Otherwise, the method tries to set the constant signal value for that port and returns True if successful.

Does not work for instance output ports, as they are always driven by their parent instances.

Parameters:

  • name

    (str) –

    The name of the port.

  • index

    (NonNegativeInt) –

    The bit index within the port.

  • sig_value

    (LogicLevel) –

    The constant signal value to be set ('0', '1', or 'Z').

Raises:

  • ObjectNotFoundError

    If no such port or port segment exists.

  • AlreadyConnectedError

    (raised by: PortSegment.tie_signal) If this segment is belongs to a load port and is already connected to a wire, from which it receives its value.

  • InvalidDirectionError

    (raised by: PortSegment.tie_signal) If this port segment belongs to an instance output port, which is driven by the instance inputs and the instance's internal logic.

  • InvalidSignalError

    (raised by: PortSegment.tie_signal) If an invalid value is provided.

has_tied_ports

has_tied_ports() -> bool

Checks the ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any ports of this instance are tied to constant values. False otherwise, i.e. all ports are connected to wires.

has_tied_inputs

has_tied_inputs() -> bool

Checks the input ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any input ports of this instance are tied to constant values. False otherwise, i.e. all input ports are connected to wires.

has_tied_outputs

has_tied_outputs() -> bool

Checks the output ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any output ports of this instance are tied to constant values. False otherwise, i.e. all output ports are connected to wires.

update_signedness

update_signedness(port_name: str) -> None

Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

Parameters:

  • port_name

    (str) –

    The name of the port, of which the signedness value is retrieved.

split

split() -> Dict[NonNegativeInt, Self]

Performs a bit-wise split on this instance.

If this instance supports splitting and has a data width of n bit, this method splits this instance into n 1-bit instances. This works for instances, where each output bit depends only on the corresponding input bit(s), e.g. an AND gate or a D-Flipflop.

Returns:

  • Dict[NonNegativeInt, Self]

    Dict[int, Instance]: An n-bit large dictionary, where each key conforms to a bit of the original instance, and each value is an 1-bit instance representing the corresponding "slice" of the original instance.

Raises:

  • SplittingUnsupportedError

    If this instance does not support splitting. Happens for any gate or instance whose behavior depends on the whole bus, and splitting would make it lose its meaning.

p2v

p2v(
    port: ANY_PORT,
    exclude_indices: Optional[List[int]] = None,
    include_indices: Optional[List[int]] = None,
) -> str

Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a Port object and converts them to their corresponding Verilog signal structure (p2v -> Port to Verilog signal syntax). For each segment of the port, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port is set to a constant, the corresponding constant wire segment placeholder is used instead. Port segments can be excluded from the conversion by providing a list of indices to the exclude_indices parameter, indicating which segments should be excluded from the conversion (e.g. segments that are known to be unconnected). Vice versa, only a certain subset of the port's segments may be converted to Verilog syntax, if include_indices is a given list of port indices. All indices not present in the list will be excluded from the conversion.

Parameters:

  • port

    (Port) –

    The Port object to convert.

  • exclude_indices

    (List[int], default: None ) –

    A list of indices to exclude from the conversion. Defaults to None.

  • include_indices

    (List[int], default: None ) –

    A list of indices (i.e. port slices) to include only for the conversion. Defaults to None.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

  • ObjectNotFoundError

    If the wire connected to a certain port segment could not be found.

  • UnsupportedOperationError

    If both exclude_indices and include_indices are specified. Only one of both may be given when calling this method.

ps2v

Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a PortSegment dictionary and converts them to their corresponding Verilog signal structure (ps2v -> PortSegment to Verilog signal syntax). For each segment, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port segment is set to a constant, the corresponding constant wire segment placeholder is used instead.

Parameters:

  • ps_dict

    (Dict[int, PortSegment]) –

    The PortSegment dictionary to convert. Each key (int) conforms to the index of the associated PortSegment object.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

set

set(
    port_name: str,
    new_signal: SignalOrLogicLevel,
    idx: Union[int, List[int]] = 0,
) -> None

Sets the signal on a port.

Parameters:

  • port_name

    (str) –

    The name of the port to set the signal on.

  • new_signal

    (Signal) –

    The new signal value.

  • idx

    (Union[int, List[int]], default: 0 ) –

    The index (or indices) to apply the given signal to. Can either be an integer (single index to set) or an iterable of integers (e.g. a list of indices). For every integer of the iterable the signal value of the corresponding port index is set to the given new_signal. Defaults to 0.

Example

from netlist_carpentry.utils.gate_factory import and_gate module = Module(name='m') a = module.create_port('a', 'input', width=6) instance = and_gate(module, 'inst', A=a)

This sets the value of bit 0 of port A to HIGH

instance.set('A', 1, 0) instance.ports['A'].signal_str 'xxxxx1'

This sets the value of bits 1, 3 and 5 of port A to LOW, leaving the other bits as they already are.

instance.set('A', 0, [1, 3, 5]) instance.ports['A'].signal_str '0x0x01'

get_result

get_result(s1: Signal, s2: Signal) -> Signal

Returns the result of this gate's operation for given Signals s1 and s2.

This method is only implemented for bitwise evaluating gates (e.g. AndGate, OrGate). This method raises an UnsupportedOperationError if used on other gates (e.g. Adder).

For vector-level operations on full signal arrays, use :meth:get_result_vector instead.

Parameters:

  • s1

    (Signal) –

    The first Signal, i.e. the first operand.

  • s2

    (Signal) –

    The second Signal, i.e. the second operand.

Raises:

Returns:

  • Signal ( Signal ) –

    The result of this gate's operation on the given signals.

get_result_vector

get_result_vector(s1: SignalArray, s2: SignalArray) -> SignalArray

Returns the result of this gate's operation for full signal vectors.

This method provides a unified interface for all binary gates to operate on :class:SignalArray (multi-bit) inputs. The default implementation iterates over each bit index and calls :meth:get_result for bitwise gates (e.g. AndGate, OrGate, XorGate). Gates that operate on the full vectors (e.g. arithmetic gates like Adder, Subtractor, or comparison gates like LessThan) override this method with their vector-level logic.

For comparison gates that produce a single bit from two N-bit inputs (e.g. LessThan, Equal), the output is a 1-bit :class:SignalArray.

Parameters:

Returns:

  • SignalArray ( SignalArray ) –

    The result of this gate's operation on the given signals. For bitwise gates, this has the same width as the inputs. For comparison/reduction gates, this is a 1-bit SignalArray.

signals_in

signals_in(idx: NonNegativeInt = 0) -> Tuple[Signal, Signal]

The input signals of the gate.

Returns:

signal_out

signal_out(idx: NonNegativeInt = 0) -> Signal

The output signal of the gate.

Returns:

  • Signal ( Signal ) –

    The output signal of the gate.

LogicAnd

Bases: BinaryNto1Gate, BaseModel

A LOGIC-AND gate.

A LOGIC-AND gate is a gate that produces a HIGH output signal if both input signals are non-zero. Otherwise, it produces a LOW output signal.

Methods:

  • change_mutability

    Change the mutability status of this instance and optionally its ports.

  • evaluate

    Evaluates the gate's output signal based on its input signals.

  • all_connections

    Returns a dictionary mapping port names to their corresponding connection paths.

  • model_post_init

    Initializes the gate's ports and connections.

  • connect

    Add connections to the specified port of this instance.

  • disconnect

    Remove an existing connection from a specified port of this instance.

  • get_connection

    Retrieve the connection path associated with a specified port and bit index.

  • modify_connection

    Modify an existing connection within a specified port of this instance.

  • connect_modify

    Add a new connection or modify an existing one within the specified port of this instance.

  • tie_port

    Set a constant signal value for the specified port and bit index.

  • has_tied_ports

    Checks the ports of this instance whether any are tied to constant values.

  • has_tied_inputs

    Checks the input ports of this instance whether any are tied to constant values.

  • has_tied_outputs

    Checks the output ports of this instance whether any are tied to constant values.

  • update_signedness

    Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

  • split

    Performs a bit-wise split on this instance.

  • p2v

    Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

  • ps2v

    Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

  • set

    Sets the signal on a port.

  • get_result

    Returns the result of this gate's operation for given Signals s1 and s2.

  • signals_in

    The input signals of the gate.

  • signal_out

    The output signal of the gate.

Attributes:

name instance-attribute

name: str

The name of the element.

!!! Do not modify this variable after instantiating it. Use NetlistElement.set_name() instead. Modifying this variable might lead to inconsistencies later on.

metadata class-attribute instance-attribute

Metadata of a netlist element.

Can be user-defined, or e. g. by Yosys (such as src for the HDL source). Is also grouped by categories, i.e. all metadata from Yosys can be accessed via Module.metadata["yosys"], or via Module.metadata.yosys, which both return a dictionary of all metadata. Read the documentation of MetaDataMixin for more information.

path property

Returns the InstancePath of the netlist element.

The InstancePath object is constructed using the element's type and its raw hierarchical path.

Returns:

  • InstancePath ( InstancePath ) –

    The hierarchical path of the netlist element.

type property

type: EType

The type of the element, which is an instance.

hierarchy_level property

hierarchy_level: int

The level of hierarchy of the element in the design.

The hierarchy level is the number of separators in the element's raw path. For example, a top-level instance has a hierarchy level of 0, while a direct submodule instance has a hierarchy level of 1.

Returns:

  • int ( int ) –

    The hierarchy level of the element.

has_parent property

has_parent: bool

Whether this object has a parent.

circuit property

circuit: 'Circuit'

The circuit object to which this netlist element belongs to.

  • For a module, returns the circuit to which the module belongs.
  • For any other netlist element, recursively returns the circuit of the parent, which ultimately leads to a module, to which the netlist element belongs.

Raises:

  • ParentNotFoundError

    If a parent cannot be resolved somewhere in the hierarchical chain.

  • ObjectNotFoundError

    If for a module no circuit is set.

has_circuit property

has_circuit: bool

Whether this netlist element has a defined circuit it belongs to.

Tries to access self.circuit and returns whether the call was successful. Can be used instead of a try-except clause around the call to NetlistElement.circuit.

locked property

locked: bool

True if this NetlistElement instance is locked (i.e. it is currently structurally unchangeable), False if it is mutable.

Can be changed via NetlistElement.change_mutability(bool).

Immutability is used to prevent accidental changes to the design.

is_placeholder_instance property

is_placeholder_instance: bool

A placeholder represents an element that does not have a specific path.

True if this NetlistElement instance represents a placeholder, False otherwise.

can_carry_signal property

can_carry_signal: bool

Whether this exact object is able to receive, pass or hold signal values.

True for ports (as they drive or receive values) and wires (as they pass the signals from driver to load ports) as well as their respective segments. False for instances and modules.

connections property

connections: Dict[str, Dict[int, WireSegmentPath]]

A dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port. Elements with no connection (i.e. the path is None) are excluded. In case these are needed, use Instance.get_connections() instead.

Example

{ 'port1': {1: WireSegmentPath('path/to/element1'), 2: WireSegmentPath('path/to/element2')}, 'port2': {1: WireSegmentPath('path/to/element3')} }

connection_str_paths property

connection_str_paths: Dict[str, Dict[int, str]]

Returns a dictionary mapping port names to their corresponding connection paths as strings.

The keys are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are the raw string paths.

Example

{ 'port1': {0: 'path.to.element1', 1: 'path.to.element2'}, 'port2': {0: 'path.to.element3'} }

ports property

A dictionary mapping port names to their corresponding Port objects.

The keys of the dictionary are the names of the ports. The values are Port objects representing the ports.

Returns:

input_ports property

input_ports: Tuple[Port[Instance], Port[Instance]]

The input ports of the gate as a 2-tuple.

output_ports property

output_ports: Tuple[Port[Instance], ...]

Returns a tuple of output ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as outputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the output ports.

has_unconnected_port_segments property

has_unconnected_port_segments: bool

Returns True if the instance has at least one unconnected port segment.

signals property

signals: Dict[str, SignalArray]

A dictionary with all signals currently present on all ports of this instance.

is_blackbox property

is_blackbox: bool

Flag indicating whether the instance represents neither a primitive element nor a module instance.

If True, this instance does not have a module definition, and is also not a basic component (i.e. a primitive gate instance) from the internal gate library, such as a gate or flip-flop.

y_width property

y_width: PositiveInt

Width of the gate, which is always 1 for gates that reduce N-bit inputs to 1 bit.

a_width property

a_width: PositiveInt

Width of the gate's A port.

b_width property

b_width: PositiveInt

Width of the gate's B port.

is_combinational property

is_combinational: bool

Whether instances of this gate are considered combinational gates.

True for combinational gates, such as AND gates or arithmetic gates. False for flip-flops and latches.

is_sequential property

is_sequential: bool

Whether instances of this gate are considered sequential gates.

False for combinational gates, such as AND gates or arithmetic gates. True for flip-flops and latches.

output_port property

output_port: Port[Instance]

The output port of the gate.

data_width property

data_width: int

The data width of this instance.

Defaults to the data width of the output port. Can be overwritten in extended classes.

In contrast to self.width, which is used for the creation and initialization, this property is linked to the data width of the output port. This property is useful when the data width of the output port can be changed.

a_signed property

a_signed: bool

The signedness of input port A.

b_signed property

b_signed: bool

The signedness of input port B.

truth_table property

truth_table: Dict[Tuple[Signal, Signal], Signal]

A simple truth table as a dictionary.

This dictionary contains the input-output mapping for unary gates that evaluate bitwise (e.g. AndGate, OrGate). Not implemented for arithmetic gates (e.g. Adder).

change_mutability

change_mutability(is_now_locked: bool, recursive: bool = False) -> Self

Change the mutability status of this instance and optionally its ports.

This method allows setting whether this instance can be modified or not. If recursive is set to True, it also applies the same mutability status to all ports of this instance.

Parameters:

  • is_now_locked

    (bool) –

    The new mutability status for this instance.

  • recursive

    (bool, default: False ) –

    Whether to apply the change recursively to its ports. Defaults to False.

evaluate

evaluate() -> None

Evaluates the gate's output signal based on its input signals.

This method is called when the gate's input signals change, and it updates the gate's output signal accordingly.

all_connections

all_connections(
    include_unconnected: bool,
) -> Dict[str, Dict[int, WireSegmentPath]]

Returns a dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port.

Parameters:

  • include_unconnected

    (bool) –

    Whether to include unconnected ports in the result.

Returns:

model_post_init

model_post_init(__context: object) -> None

Initializes the gate's ports and connections.

This method is called after the gate's attributes have been initialized, and it sets up the gate's ports and connections.

connect

connect(
    port_name: str,
    ws_path: Optional[WireSegmentPath],
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add connections to the specified port of this instance.

This method can establish multiple connections if a range of indices is provided.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection(s) should be established.

  • ws_path

    (Optional[WireSegmentPath]) –

    The path of the wire segment that will be connected to this port. If None, the associated port (segment) remains unconnected.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

Raises:

  • ObjectLockedError

    If this instance is currently locked, and no connection can be made.

disconnect

disconnect(port_name: str, index: Optional[int] = None) -> None

Remove an existing connection from a specified port of this instance.

This method disconnects the wire segment at the given index within the specified port_name.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be removed.

  • index

    (Optional[int], default: None ) –

    The bit index within the port for this disconnection. Defaults to None, which completely disconnects the port.

Raises:

get_connection

get_connection(
    port_name: str, index: Optional[NonNegativeInt] = None
) -> Union[WireSegmentPath, Dict[int, WireSegmentPath], None]

Retrieve the connection path associated with a specified port and bit index.

If index is provided, this method returns the wire segment path connected to that specific bit within the port. Otherwise, it returns all connections for the given port as a dictionary mapping indices to WireSegmentPaths.

Parameters:

  • port_name

    (str) –

    The name of the port for which to retrieve the connection(s).

  • index

    (Optional[NonNegativeInt], default: None ) –

    The bit index within the port. Defaults to None.

Returns:

modify_connection

modify_connection(
    port_name: str, ws_path: WireSegmentPath, index: NonNegativeInt = 0
) -> None

Modify an existing connection within a specified port of this instance.

This method updates the wire segment path at the given index within the specified port_name. If the index does not exist yet, it is newly added, changing the width of the port.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be modified.

  • ws_path

    (WireSegmentPath) –

    The new wire segment path for this connection.

  • index

    (NonNegativeInt, default: 0 ) –

    The bit index within the port. Defaults to 0.

connect_modify

connect_modify(
    port_name: str,
    ws_path: WireSegmentPath,
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add a new connection or modify an existing one within the specified port of this instance.

If the connection already exists at the given index and port_name, it will be modified. Otherwise, a new connection is added.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be established or updated.

  • ws_path

    (WireSegmentPath) –

    The path of the wire segment that will be connected to this port.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

tie_port

tie_port(name: str, index: NonNegativeInt, sig_value: LogicLevel) -> None

Set a constant signal value for the specified port and bit index.

If the specified port does not exist, an error message is logged and the function returns False. Otherwise, the method tries to set the constant signal value for that port and returns True if successful.

Does not work for instance output ports, as they are always driven by their parent instances.

Parameters:

  • name

    (str) –

    The name of the port.

  • index

    (NonNegativeInt) –

    The bit index within the port.

  • sig_value

    (LogicLevel) –

    The constant signal value to be set ('0', '1', or 'Z').

Raises:

  • ObjectNotFoundError

    If no such port or port segment exists.

  • AlreadyConnectedError

    (raised by: PortSegment.tie_signal) If this segment is belongs to a load port and is already connected to a wire, from which it receives its value.

  • InvalidDirectionError

    (raised by: PortSegment.tie_signal) If this port segment belongs to an instance output port, which is driven by the instance inputs and the instance's internal logic.

  • InvalidSignalError

    (raised by: PortSegment.tie_signal) If an invalid value is provided.

has_tied_ports

has_tied_ports() -> bool

Checks the ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any ports of this instance are tied to constant values. False otherwise, i.e. all ports are connected to wires.

has_tied_inputs

has_tied_inputs() -> bool

Checks the input ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any input ports of this instance are tied to constant values. False otherwise, i.e. all input ports are connected to wires.

has_tied_outputs

has_tied_outputs() -> bool

Checks the output ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any output ports of this instance are tied to constant values. False otherwise, i.e. all output ports are connected to wires.

update_signedness

update_signedness(port_name: str) -> None

Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

Parameters:

  • port_name

    (str) –

    The name of the port, of which the signedness value is retrieved.

split

split() -> Dict[NonNegativeInt, Self]

Performs a bit-wise split on this instance.

If this instance supports splitting and has a data width of n bit, this method splits this instance into n 1-bit instances. This works for instances, where each output bit depends only on the corresponding input bit(s), e.g. an AND gate or a D-Flipflop.

Returns:

  • Dict[NonNegativeInt, Self]

    Dict[int, Instance]: An n-bit large dictionary, where each key conforms to a bit of the original instance, and each value is an 1-bit instance representing the corresponding "slice" of the original instance.

Raises:

  • SplittingUnsupportedError

    If this instance does not support splitting. Happens for any gate or instance whose behavior depends on the whole bus, and splitting would make it lose its meaning.

p2v

p2v(
    port: ANY_PORT,
    exclude_indices: Optional[List[int]] = None,
    include_indices: Optional[List[int]] = None,
) -> str

Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a Port object and converts them to their corresponding Verilog signal structure (p2v -> Port to Verilog signal syntax). For each segment of the port, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port is set to a constant, the corresponding constant wire segment placeholder is used instead. Port segments can be excluded from the conversion by providing a list of indices to the exclude_indices parameter, indicating which segments should be excluded from the conversion (e.g. segments that are known to be unconnected). Vice versa, only a certain subset of the port's segments may be converted to Verilog syntax, if include_indices is a given list of port indices. All indices not present in the list will be excluded from the conversion.

Parameters:

  • port

    (Port) –

    The Port object to convert.

  • exclude_indices

    (List[int], default: None ) –

    A list of indices to exclude from the conversion. Defaults to None.

  • include_indices

    (List[int], default: None ) –

    A list of indices (i.e. port slices) to include only for the conversion. Defaults to None.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

  • ObjectNotFoundError

    If the wire connected to a certain port segment could not be found.

  • UnsupportedOperationError

    If both exclude_indices and include_indices are specified. Only one of both may be given when calling this method.

ps2v

Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a PortSegment dictionary and converts them to their corresponding Verilog signal structure (ps2v -> PortSegment to Verilog signal syntax). For each segment, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port segment is set to a constant, the corresponding constant wire segment placeholder is used instead.

Parameters:

  • ps_dict

    (Dict[int, PortSegment]) –

    The PortSegment dictionary to convert. Each key (int) conforms to the index of the associated PortSegment object.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

set

set(
    port_name: str,
    new_signal: SignalOrLogicLevel,
    idx: Union[int, List[int]] = 0,
) -> None

Sets the signal on a port.

Parameters:

  • port_name

    (str) –

    The name of the port to set the signal on.

  • new_signal

    (Signal) –

    The new signal value.

  • idx

    (Union[int, List[int]], default: 0 ) –

    The index (or indices) to apply the given signal to. Can either be an integer (single index to set) or an iterable of integers (e.g. a list of indices). For every integer of the iterable the signal value of the corresponding port index is set to the given new_signal. Defaults to 0.

Example

from netlist_carpentry.utils.gate_factory import and_gate module = Module(name='m') a = module.create_port('a', 'input', width=6) instance = and_gate(module, 'inst', A=a)

This sets the value of bit 0 of port A to HIGH

instance.set('A', 1, 0) instance.ports['A'].signal_str 'xxxxx1'

This sets the value of bits 1, 3 and 5 of port A to LOW, leaving the other bits as they already are.

instance.set('A', 0, [1, 3, 5]) instance.ports['A'].signal_str '0x0x01'

get_result

get_result(s1: Signal, s2: Signal) -> Signal

Returns the result of this gate's operation for given Signals s1 and s2.

This method is only implemented for bitwise evaluating gates (e.g. AndGate, OrGate). This method raises an UnsupportedOperationError if used on other gates (e.g. Adder).

For vector-level operations on full signal arrays, use :meth:get_result_vector instead.

Parameters:

  • s1

    (Signal) –

    The first Signal, i.e. the first operand.

  • s2

    (Signal) –

    The second Signal, i.e. the second operand.

Raises:

Returns:

  • Signal ( Signal ) –

    The result of this gate's operation on the given signals.

signals_in

signals_in(idx: NonNegativeInt = 0) -> Tuple[Signal, Signal]

The input signals of the gate.

Returns:

signal_out

signal_out(idx: NonNegativeInt = 0) -> Signal

The output signal of the gate.

Returns:

  • Signal ( Signal ) –

    The output signal of the gate.

LogicOr

Bases: BinaryNto1Gate, BaseModel

A LOGIC-OR gate.

A LOGIC-OR gate is a gate that produces a HIGH output signal if at least one of both input signals is non-zero. Otherwise, it produces a LOW output signal.

Methods:

  • change_mutability

    Change the mutability status of this instance and optionally its ports.

  • evaluate

    Evaluates the gate's output signal based on its input signals.

  • all_connections

    Returns a dictionary mapping port names to their corresponding connection paths.

  • model_post_init

    Initializes the gate's ports and connections.

  • connect

    Add connections to the specified port of this instance.

  • disconnect

    Remove an existing connection from a specified port of this instance.

  • get_connection

    Retrieve the connection path associated with a specified port and bit index.

  • modify_connection

    Modify an existing connection within a specified port of this instance.

  • connect_modify

    Add a new connection or modify an existing one within the specified port of this instance.

  • tie_port

    Set a constant signal value for the specified port and bit index.

  • has_tied_ports

    Checks the ports of this instance whether any are tied to constant values.

  • has_tied_inputs

    Checks the input ports of this instance whether any are tied to constant values.

  • has_tied_outputs

    Checks the output ports of this instance whether any are tied to constant values.

  • update_signedness

    Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

  • split

    Performs a bit-wise split on this instance.

  • p2v

    Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

  • ps2v

    Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

  • set

    Sets the signal on a port.

  • get_result

    Returns the result of this gate's operation for given Signals s1 and s2.

  • signals_in

    The input signals of the gate.

  • signal_out

    The output signal of the gate.

Attributes:

name instance-attribute

name: str

The name of the element.

!!! Do not modify this variable after instantiating it. Use NetlistElement.set_name() instead. Modifying this variable might lead to inconsistencies later on.

metadata class-attribute instance-attribute

Metadata of a netlist element.

Can be user-defined, or e. g. by Yosys (such as src for the HDL source). Is also grouped by categories, i.e. all metadata from Yosys can be accessed via Module.metadata["yosys"], or via Module.metadata.yosys, which both return a dictionary of all metadata. Read the documentation of MetaDataMixin for more information.

path property

Returns the InstancePath of the netlist element.

The InstancePath object is constructed using the element's type and its raw hierarchical path.

Returns:

  • InstancePath ( InstancePath ) –

    The hierarchical path of the netlist element.

type property

type: EType

The type of the element, which is an instance.

hierarchy_level property

hierarchy_level: int

The level of hierarchy of the element in the design.

The hierarchy level is the number of separators in the element's raw path. For example, a top-level instance has a hierarchy level of 0, while a direct submodule instance has a hierarchy level of 1.

Returns:

  • int ( int ) –

    The hierarchy level of the element.

has_parent property

has_parent: bool

Whether this object has a parent.

circuit property

circuit: 'Circuit'

The circuit object to which this netlist element belongs to.

  • For a module, returns the circuit to which the module belongs.
  • For any other netlist element, recursively returns the circuit of the parent, which ultimately leads to a module, to which the netlist element belongs.

Raises:

  • ParentNotFoundError

    If a parent cannot be resolved somewhere in the hierarchical chain.

  • ObjectNotFoundError

    If for a module no circuit is set.

has_circuit property

has_circuit: bool

Whether this netlist element has a defined circuit it belongs to.

Tries to access self.circuit and returns whether the call was successful. Can be used instead of a try-except clause around the call to NetlistElement.circuit.

locked property

locked: bool

True if this NetlistElement instance is locked (i.e. it is currently structurally unchangeable), False if it is mutable.

Can be changed via NetlistElement.change_mutability(bool).

Immutability is used to prevent accidental changes to the design.

is_placeholder_instance property

is_placeholder_instance: bool

A placeholder represents an element that does not have a specific path.

True if this NetlistElement instance represents a placeholder, False otherwise.

can_carry_signal property

can_carry_signal: bool

Whether this exact object is able to receive, pass or hold signal values.

True for ports (as they drive or receive values) and wires (as they pass the signals from driver to load ports) as well as their respective segments. False for instances and modules.

connections property

connections: Dict[str, Dict[int, WireSegmentPath]]

A dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port. Elements with no connection (i.e. the path is None) are excluded. In case these are needed, use Instance.get_connections() instead.

Example

{ 'port1': {1: WireSegmentPath('path/to/element1'), 2: WireSegmentPath('path/to/element2')}, 'port2': {1: WireSegmentPath('path/to/element3')} }

connection_str_paths property

connection_str_paths: Dict[str, Dict[int, str]]

Returns a dictionary mapping port names to their corresponding connection paths as strings.

The keys are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are the raw string paths.

Example

{ 'port1': {0: 'path.to.element1', 1: 'path.to.element2'}, 'port2': {0: 'path.to.element3'} }

ports property

A dictionary mapping port names to their corresponding Port objects.

The keys of the dictionary are the names of the ports. The values are Port objects representing the ports.

Returns:

input_ports property

input_ports: Tuple[Port[Instance], Port[Instance]]

The input ports of the gate as a 2-tuple.

output_ports property

output_ports: Tuple[Port[Instance], ...]

Returns a tuple of output ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as outputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the output ports.

has_unconnected_port_segments property

has_unconnected_port_segments: bool

Returns True if the instance has at least one unconnected port segment.

signals property

signals: Dict[str, SignalArray]

A dictionary with all signals currently present on all ports of this instance.

is_blackbox property

is_blackbox: bool

Flag indicating whether the instance represents neither a primitive element nor a module instance.

If True, this instance does not have a module definition, and is also not a basic component (i.e. a primitive gate instance) from the internal gate library, such as a gate or flip-flop.

y_width property

y_width: PositiveInt

Width of the gate, which is always 1 for gates that reduce N-bit inputs to 1 bit.

a_width property

a_width: PositiveInt

Width of the gate's A port.

b_width property

b_width: PositiveInt

Width of the gate's B port.

is_combinational property

is_combinational: bool

Whether instances of this gate are considered combinational gates.

True for combinational gates, such as AND gates or arithmetic gates. False for flip-flops and latches.

is_sequential property

is_sequential: bool

Whether instances of this gate are considered sequential gates.

False for combinational gates, such as AND gates or arithmetic gates. True for flip-flops and latches.

output_port property

output_port: Port[Instance]

The output port of the gate.

data_width property

data_width: int

The data width of this instance.

Defaults to the data width of the output port. Can be overwritten in extended classes.

In contrast to self.width, which is used for the creation and initialization, this property is linked to the data width of the output port. This property is useful when the data width of the output port can be changed.

a_signed property

a_signed: bool

The signedness of input port A.

b_signed property

b_signed: bool

The signedness of input port B.

truth_table property

truth_table: Dict[Tuple[Signal, Signal], Signal]

A simple truth table as a dictionary.

This dictionary contains the input-output mapping for unary gates that evaluate bitwise (e.g. AndGate, OrGate). Not implemented for arithmetic gates (e.g. Adder).

change_mutability

change_mutability(is_now_locked: bool, recursive: bool = False) -> Self

Change the mutability status of this instance and optionally its ports.

This method allows setting whether this instance can be modified or not. If recursive is set to True, it also applies the same mutability status to all ports of this instance.

Parameters:

  • is_now_locked

    (bool) –

    The new mutability status for this instance.

  • recursive

    (bool, default: False ) –

    Whether to apply the change recursively to its ports. Defaults to False.

evaluate

evaluate() -> None

Evaluates the gate's output signal based on its input signals.

This method is called when the gate's input signals change, and it updates the gate's output signal accordingly.

all_connections

all_connections(
    include_unconnected: bool,
) -> Dict[str, Dict[int, WireSegmentPath]]

Returns a dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port.

Parameters:

  • include_unconnected

    (bool) –

    Whether to include unconnected ports in the result.

Returns:

model_post_init

model_post_init(__context: object) -> None

Initializes the gate's ports and connections.

This method is called after the gate's attributes have been initialized, and it sets up the gate's ports and connections.

connect

connect(
    port_name: str,
    ws_path: Optional[WireSegmentPath],
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add connections to the specified port of this instance.

This method can establish multiple connections if a range of indices is provided.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection(s) should be established.

  • ws_path

    (Optional[WireSegmentPath]) –

    The path of the wire segment that will be connected to this port. If None, the associated port (segment) remains unconnected.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

Raises:

  • ObjectLockedError

    If this instance is currently locked, and no connection can be made.

disconnect

disconnect(port_name: str, index: Optional[int] = None) -> None

Remove an existing connection from a specified port of this instance.

This method disconnects the wire segment at the given index within the specified port_name.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be removed.

  • index

    (Optional[int], default: None ) –

    The bit index within the port for this disconnection. Defaults to None, which completely disconnects the port.

Raises:

get_connection

get_connection(
    port_name: str, index: Optional[NonNegativeInt] = None
) -> Union[WireSegmentPath, Dict[int, WireSegmentPath], None]

Retrieve the connection path associated with a specified port and bit index.

If index is provided, this method returns the wire segment path connected to that specific bit within the port. Otherwise, it returns all connections for the given port as a dictionary mapping indices to WireSegmentPaths.

Parameters:

  • port_name

    (str) –

    The name of the port for which to retrieve the connection(s).

  • index

    (Optional[NonNegativeInt], default: None ) –

    The bit index within the port. Defaults to None.

Returns:

modify_connection

modify_connection(
    port_name: str, ws_path: WireSegmentPath, index: NonNegativeInt = 0
) -> None

Modify an existing connection within a specified port of this instance.

This method updates the wire segment path at the given index within the specified port_name. If the index does not exist yet, it is newly added, changing the width of the port.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be modified.

  • ws_path

    (WireSegmentPath) –

    The new wire segment path for this connection.

  • index

    (NonNegativeInt, default: 0 ) –

    The bit index within the port. Defaults to 0.

connect_modify

connect_modify(
    port_name: str,
    ws_path: WireSegmentPath,
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add a new connection or modify an existing one within the specified port of this instance.

If the connection already exists at the given index and port_name, it will be modified. Otherwise, a new connection is added.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be established or updated.

  • ws_path

    (WireSegmentPath) –

    The path of the wire segment that will be connected to this port.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

tie_port

tie_port(name: str, index: NonNegativeInt, sig_value: LogicLevel) -> None

Set a constant signal value for the specified port and bit index.

If the specified port does not exist, an error message is logged and the function returns False. Otherwise, the method tries to set the constant signal value for that port and returns True if successful.

Does not work for instance output ports, as they are always driven by their parent instances.

Parameters:

  • name

    (str) –

    The name of the port.

  • index

    (NonNegativeInt) –

    The bit index within the port.

  • sig_value

    (LogicLevel) –

    The constant signal value to be set ('0', '1', or 'Z').

Raises:

  • ObjectNotFoundError

    If no such port or port segment exists.

  • AlreadyConnectedError

    (raised by: PortSegment.tie_signal) If this segment is belongs to a load port and is already connected to a wire, from which it receives its value.

  • InvalidDirectionError

    (raised by: PortSegment.tie_signal) If this port segment belongs to an instance output port, which is driven by the instance inputs and the instance's internal logic.

  • InvalidSignalError

    (raised by: PortSegment.tie_signal) If an invalid value is provided.

has_tied_ports

has_tied_ports() -> bool

Checks the ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any ports of this instance are tied to constant values. False otherwise, i.e. all ports are connected to wires.

has_tied_inputs

has_tied_inputs() -> bool

Checks the input ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any input ports of this instance are tied to constant values. False otherwise, i.e. all input ports are connected to wires.

has_tied_outputs

has_tied_outputs() -> bool

Checks the output ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any output ports of this instance are tied to constant values. False otherwise, i.e. all output ports are connected to wires.

update_signedness

update_signedness(port_name: str) -> None

Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

Parameters:

  • port_name

    (str) –

    The name of the port, of which the signedness value is retrieved.

split

split() -> Dict[NonNegativeInt, Self]

Performs a bit-wise split on this instance.

If this instance supports splitting and has a data width of n bit, this method splits this instance into n 1-bit instances. This works for instances, where each output bit depends only on the corresponding input bit(s), e.g. an AND gate or a D-Flipflop.

Returns:

  • Dict[NonNegativeInt, Self]

    Dict[int, Instance]: An n-bit large dictionary, where each key conforms to a bit of the original instance, and each value is an 1-bit instance representing the corresponding "slice" of the original instance.

Raises:

  • SplittingUnsupportedError

    If this instance does not support splitting. Happens for any gate or instance whose behavior depends on the whole bus, and splitting would make it lose its meaning.

p2v

p2v(
    port: ANY_PORT,
    exclude_indices: Optional[List[int]] = None,
    include_indices: Optional[List[int]] = None,
) -> str

Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a Port object and converts them to their corresponding Verilog signal structure (p2v -> Port to Verilog signal syntax). For each segment of the port, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port is set to a constant, the corresponding constant wire segment placeholder is used instead. Port segments can be excluded from the conversion by providing a list of indices to the exclude_indices parameter, indicating which segments should be excluded from the conversion (e.g. segments that are known to be unconnected). Vice versa, only a certain subset of the port's segments may be converted to Verilog syntax, if include_indices is a given list of port indices. All indices not present in the list will be excluded from the conversion.

Parameters:

  • port

    (Port) –

    The Port object to convert.

  • exclude_indices

    (List[int], default: None ) –

    A list of indices to exclude from the conversion. Defaults to None.

  • include_indices

    (List[int], default: None ) –

    A list of indices (i.e. port slices) to include only for the conversion. Defaults to None.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

  • ObjectNotFoundError

    If the wire connected to a certain port segment could not be found.

  • UnsupportedOperationError

    If both exclude_indices and include_indices are specified. Only one of both may be given when calling this method.

ps2v

Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a PortSegment dictionary and converts them to their corresponding Verilog signal structure (ps2v -> PortSegment to Verilog signal syntax). For each segment, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port segment is set to a constant, the corresponding constant wire segment placeholder is used instead.

Parameters:

  • ps_dict

    (Dict[int, PortSegment]) –

    The PortSegment dictionary to convert. Each key (int) conforms to the index of the associated PortSegment object.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

set

set(
    port_name: str,
    new_signal: SignalOrLogicLevel,
    idx: Union[int, List[int]] = 0,
) -> None

Sets the signal on a port.

Parameters:

  • port_name

    (str) –

    The name of the port to set the signal on.

  • new_signal

    (Signal) –

    The new signal value.

  • idx

    (Union[int, List[int]], default: 0 ) –

    The index (or indices) to apply the given signal to. Can either be an integer (single index to set) or an iterable of integers (e.g. a list of indices). For every integer of the iterable the signal value of the corresponding port index is set to the given new_signal. Defaults to 0.

Example

from netlist_carpentry.utils.gate_factory import and_gate module = Module(name='m') a = module.create_port('a', 'input', width=6) instance = and_gate(module, 'inst', A=a)

This sets the value of bit 0 of port A to HIGH

instance.set('A', 1, 0) instance.ports['A'].signal_str 'xxxxx1'

This sets the value of bits 1, 3 and 5 of port A to LOW, leaving the other bits as they already are.

instance.set('A', 0, [1, 3, 5]) instance.ports['A'].signal_str '0x0x01'

get_result

get_result(s1: Signal, s2: Signal) -> Signal

Returns the result of this gate's operation for given Signals s1 and s2.

This method is only implemented for bitwise evaluating gates (e.g. AndGate, OrGate). This method raises an UnsupportedOperationError if used on other gates (e.g. Adder).

For vector-level operations on full signal arrays, use :meth:get_result_vector instead.

Parameters:

  • s1

    (Signal) –

    The first Signal, i.e. the first operand.

  • s2

    (Signal) –

    The second Signal, i.e. the second operand.

Raises:

Returns:

  • Signal ( Signal ) –

    The result of this gate's operation on the given signals.

signals_in

signals_in(idx: NonNegativeInt = 0) -> Tuple[Signal, Signal]

The input signals of the gate.

Returns:

signal_out

signal_out(idx: NonNegativeInt = 0) -> Signal

The output signal of the gate.

Returns:

  • Signal ( Signal ) –

    The output signal of the gate.

LessThan

Bases: BinaryNto1Gate, BaseModel

A LESS-THAN gate.

A LESS-THAN gate is a gate that produces a HIGH output signal only if its "left" input signal value is less than its "right" input signal. Otherwise, it produces a LOW output signal.

Methods:

  • change_mutability

    Change the mutability status of this instance and optionally its ports.

  • evaluate

    Evaluates the gate's output signal based on its input signals.

  • all_connections

    Returns a dictionary mapping port names to their corresponding connection paths.

  • model_post_init

    Initializes the gate's ports and connections.

  • connect

    Add connections to the specified port of this instance.

  • disconnect

    Remove an existing connection from a specified port of this instance.

  • get_connection

    Retrieve the connection path associated with a specified port and bit index.

  • modify_connection

    Modify an existing connection within a specified port of this instance.

  • connect_modify

    Add a new connection or modify an existing one within the specified port of this instance.

  • tie_port

    Set a constant signal value for the specified port and bit index.

  • has_tied_ports

    Checks the ports of this instance whether any are tied to constant values.

  • has_tied_inputs

    Checks the input ports of this instance whether any are tied to constant values.

  • has_tied_outputs

    Checks the output ports of this instance whether any are tied to constant values.

  • update_signedness

    Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

  • split

    Performs a bit-wise split on this instance.

  • p2v

    Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

  • ps2v

    Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

  • set

    Sets the signal on a port.

  • get_result

    Returns the result of this gate's operation for given Signals s1 and s2.

  • signals_in

    The input signals of the gate.

  • signal_out

    The output signal of the gate.

Attributes:

name instance-attribute

name: str

The name of the element.

!!! Do not modify this variable after instantiating it. Use NetlistElement.set_name() instead. Modifying this variable might lead to inconsistencies later on.

metadata class-attribute instance-attribute

Metadata of a netlist element.

Can be user-defined, or e. g. by Yosys (such as src for the HDL source). Is also grouped by categories, i.e. all metadata from Yosys can be accessed via Module.metadata["yosys"], or via Module.metadata.yosys, which both return a dictionary of all metadata. Read the documentation of MetaDataMixin for more information.

path property

Returns the InstancePath of the netlist element.

The InstancePath object is constructed using the element's type and its raw hierarchical path.

Returns:

  • InstancePath ( InstancePath ) –

    The hierarchical path of the netlist element.

type property

type: EType

The type of the element, which is an instance.

hierarchy_level property

hierarchy_level: int

The level of hierarchy of the element in the design.

The hierarchy level is the number of separators in the element's raw path. For example, a top-level instance has a hierarchy level of 0, while a direct submodule instance has a hierarchy level of 1.

Returns:

  • int ( int ) –

    The hierarchy level of the element.

has_parent property

has_parent: bool

Whether this object has a parent.

circuit property

circuit: 'Circuit'

The circuit object to which this netlist element belongs to.

  • For a module, returns the circuit to which the module belongs.
  • For any other netlist element, recursively returns the circuit of the parent, which ultimately leads to a module, to which the netlist element belongs.

Raises:

  • ParentNotFoundError

    If a parent cannot be resolved somewhere in the hierarchical chain.

  • ObjectNotFoundError

    If for a module no circuit is set.

has_circuit property

has_circuit: bool

Whether this netlist element has a defined circuit it belongs to.

Tries to access self.circuit and returns whether the call was successful. Can be used instead of a try-except clause around the call to NetlistElement.circuit.

locked property

locked: bool

True if this NetlistElement instance is locked (i.e. it is currently structurally unchangeable), False if it is mutable.

Can be changed via NetlistElement.change_mutability(bool).

Immutability is used to prevent accidental changes to the design.

is_placeholder_instance property

is_placeholder_instance: bool

A placeholder represents an element that does not have a specific path.

True if this NetlistElement instance represents a placeholder, False otherwise.

can_carry_signal property

can_carry_signal: bool

Whether this exact object is able to receive, pass or hold signal values.

True for ports (as they drive or receive values) and wires (as they pass the signals from driver to load ports) as well as their respective segments. False for instances and modules.

connections property

connections: Dict[str, Dict[int, WireSegmentPath]]

A dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port. Elements with no connection (i.e. the path is None) are excluded. In case these are needed, use Instance.get_connections() instead.

Example

{ 'port1': {1: WireSegmentPath('path/to/element1'), 2: WireSegmentPath('path/to/element2')}, 'port2': {1: WireSegmentPath('path/to/element3')} }

connection_str_paths property

connection_str_paths: Dict[str, Dict[int, str]]

Returns a dictionary mapping port names to their corresponding connection paths as strings.

The keys are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are the raw string paths.

Example

{ 'port1': {0: 'path.to.element1', 1: 'path.to.element2'}, 'port2': {0: 'path.to.element3'} }

ports property

A dictionary mapping port names to their corresponding Port objects.

The keys of the dictionary are the names of the ports. The values are Port objects representing the ports.

Returns:

input_ports property

input_ports: Tuple[Port[Instance], Port[Instance]]

The input ports of the gate as a 2-tuple.

output_ports property

output_ports: Tuple[Port[Instance], ...]

Returns a tuple of output ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as outputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the output ports.

has_unconnected_port_segments property

has_unconnected_port_segments: bool

Returns True if the instance has at least one unconnected port segment.

signals property

signals: Dict[str, SignalArray]

A dictionary with all signals currently present on all ports of this instance.

is_blackbox property

is_blackbox: bool

Flag indicating whether the instance represents neither a primitive element nor a module instance.

If True, this instance does not have a module definition, and is also not a basic component (i.e. a primitive gate instance) from the internal gate library, such as a gate or flip-flop.

y_width property

y_width: PositiveInt

Width of the gate, which is always 1 for gates that reduce N-bit inputs to 1 bit.

a_width property

a_width: PositiveInt

Width of the gate's A port.

b_width property

b_width: PositiveInt

Width of the gate's B port.

is_combinational property

is_combinational: bool

Whether instances of this gate are considered combinational gates.

True for combinational gates, such as AND gates or arithmetic gates. False for flip-flops and latches.

is_sequential property

is_sequential: bool

Whether instances of this gate are considered sequential gates.

False for combinational gates, such as AND gates or arithmetic gates. True for flip-flops and latches.

output_port property

output_port: Port[Instance]

The output port of the gate.

data_width property

data_width: int

The data width of this instance.

Defaults to the data width of the output port. Can be overwritten in extended classes.

In contrast to self.width, which is used for the creation and initialization, this property is linked to the data width of the output port. This property is useful when the data width of the output port can be changed.

a_signed property

a_signed: bool

The signedness of input port A.

b_signed property

b_signed: bool

The signedness of input port B.

truth_table property

truth_table: Dict[Tuple[Signal, Signal], Signal]

A simple truth table as a dictionary.

This dictionary contains the input-output mapping for unary gates that evaluate bitwise (e.g. AndGate, OrGate). Not implemented for arithmetic gates (e.g. Adder).

change_mutability

change_mutability(is_now_locked: bool, recursive: bool = False) -> Self

Change the mutability status of this instance and optionally its ports.

This method allows setting whether this instance can be modified or not. If recursive is set to True, it also applies the same mutability status to all ports of this instance.

Parameters:

  • is_now_locked

    (bool) –

    The new mutability status for this instance.

  • recursive

    (bool, default: False ) –

    Whether to apply the change recursively to its ports. Defaults to False.

evaluate

evaluate() -> None

Evaluates the gate's output signal based on its input signals.

This method is called when the gate's input signals change, and it updates the gate's output signal accordingly.

all_connections

all_connections(
    include_unconnected: bool,
) -> Dict[str, Dict[int, WireSegmentPath]]

Returns a dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port.

Parameters:

  • include_unconnected

    (bool) –

    Whether to include unconnected ports in the result.

Returns:

model_post_init

model_post_init(__context: object) -> None

Initializes the gate's ports and connections.

This method is called after the gate's attributes have been initialized, and it sets up the gate's ports and connections.

connect

connect(
    port_name: str,
    ws_path: Optional[WireSegmentPath],
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add connections to the specified port of this instance.

This method can establish multiple connections if a range of indices is provided.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection(s) should be established.

  • ws_path

    (Optional[WireSegmentPath]) –

    The path of the wire segment that will be connected to this port. If None, the associated port (segment) remains unconnected.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

Raises:

  • ObjectLockedError

    If this instance is currently locked, and no connection can be made.

disconnect

disconnect(port_name: str, index: Optional[int] = None) -> None

Remove an existing connection from a specified port of this instance.

This method disconnects the wire segment at the given index within the specified port_name.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be removed.

  • index

    (Optional[int], default: None ) –

    The bit index within the port for this disconnection. Defaults to None, which completely disconnects the port.

Raises:

get_connection

get_connection(
    port_name: str, index: Optional[NonNegativeInt] = None
) -> Union[WireSegmentPath, Dict[int, WireSegmentPath], None]

Retrieve the connection path associated with a specified port and bit index.

If index is provided, this method returns the wire segment path connected to that specific bit within the port. Otherwise, it returns all connections for the given port as a dictionary mapping indices to WireSegmentPaths.

Parameters:

  • port_name

    (str) –

    The name of the port for which to retrieve the connection(s).

  • index

    (Optional[NonNegativeInt], default: None ) –

    The bit index within the port. Defaults to None.

Returns:

modify_connection

modify_connection(
    port_name: str, ws_path: WireSegmentPath, index: NonNegativeInt = 0
) -> None

Modify an existing connection within a specified port of this instance.

This method updates the wire segment path at the given index within the specified port_name. If the index does not exist yet, it is newly added, changing the width of the port.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be modified.

  • ws_path

    (WireSegmentPath) –

    The new wire segment path for this connection.

  • index

    (NonNegativeInt, default: 0 ) –

    The bit index within the port. Defaults to 0.

connect_modify

connect_modify(
    port_name: str,
    ws_path: WireSegmentPath,
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add a new connection or modify an existing one within the specified port of this instance.

If the connection already exists at the given index and port_name, it will be modified. Otherwise, a new connection is added.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be established or updated.

  • ws_path

    (WireSegmentPath) –

    The path of the wire segment that will be connected to this port.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

tie_port

tie_port(name: str, index: NonNegativeInt, sig_value: LogicLevel) -> None

Set a constant signal value for the specified port and bit index.

If the specified port does not exist, an error message is logged and the function returns False. Otherwise, the method tries to set the constant signal value for that port and returns True if successful.

Does not work for instance output ports, as they are always driven by their parent instances.

Parameters:

  • name

    (str) –

    The name of the port.

  • index

    (NonNegativeInt) –

    The bit index within the port.

  • sig_value

    (LogicLevel) –

    The constant signal value to be set ('0', '1', or 'Z').

Raises:

  • ObjectNotFoundError

    If no such port or port segment exists.

  • AlreadyConnectedError

    (raised by: PortSegment.tie_signal) If this segment is belongs to a load port and is already connected to a wire, from which it receives its value.

  • InvalidDirectionError

    (raised by: PortSegment.tie_signal) If this port segment belongs to an instance output port, which is driven by the instance inputs and the instance's internal logic.

  • InvalidSignalError

    (raised by: PortSegment.tie_signal) If an invalid value is provided.

has_tied_ports

has_tied_ports() -> bool

Checks the ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any ports of this instance are tied to constant values. False otherwise, i.e. all ports are connected to wires.

has_tied_inputs

has_tied_inputs() -> bool

Checks the input ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any input ports of this instance are tied to constant values. False otherwise, i.e. all input ports are connected to wires.

has_tied_outputs

has_tied_outputs() -> bool

Checks the output ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any output ports of this instance are tied to constant values. False otherwise, i.e. all output ports are connected to wires.

update_signedness

update_signedness(port_name: str) -> None

Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

Parameters:

  • port_name

    (str) –

    The name of the port, of which the signedness value is retrieved.

split

split() -> Dict[NonNegativeInt, Self]

Performs a bit-wise split on this instance.

If this instance supports splitting and has a data width of n bit, this method splits this instance into n 1-bit instances. This works for instances, where each output bit depends only on the corresponding input bit(s), e.g. an AND gate or a D-Flipflop.

Returns:

  • Dict[NonNegativeInt, Self]

    Dict[int, Instance]: An n-bit large dictionary, where each key conforms to a bit of the original instance, and each value is an 1-bit instance representing the corresponding "slice" of the original instance.

Raises:

  • SplittingUnsupportedError

    If this instance does not support splitting. Happens for any gate or instance whose behavior depends on the whole bus, and splitting would make it lose its meaning.

p2v

p2v(
    port: ANY_PORT,
    exclude_indices: Optional[List[int]] = None,
    include_indices: Optional[List[int]] = None,
) -> str

Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a Port object and converts them to their corresponding Verilog signal structure (p2v -> Port to Verilog signal syntax). For each segment of the port, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port is set to a constant, the corresponding constant wire segment placeholder is used instead. Port segments can be excluded from the conversion by providing a list of indices to the exclude_indices parameter, indicating which segments should be excluded from the conversion (e.g. segments that are known to be unconnected). Vice versa, only a certain subset of the port's segments may be converted to Verilog syntax, if include_indices is a given list of port indices. All indices not present in the list will be excluded from the conversion.

Parameters:

  • port

    (Port) –

    The Port object to convert.

  • exclude_indices

    (List[int], default: None ) –

    A list of indices to exclude from the conversion. Defaults to None.

  • include_indices

    (List[int], default: None ) –

    A list of indices (i.e. port slices) to include only for the conversion. Defaults to None.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

  • ObjectNotFoundError

    If the wire connected to a certain port segment could not be found.

  • UnsupportedOperationError

    If both exclude_indices and include_indices are specified. Only one of both may be given when calling this method.

ps2v

Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a PortSegment dictionary and converts them to their corresponding Verilog signal structure (ps2v -> PortSegment to Verilog signal syntax). For each segment, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port segment is set to a constant, the corresponding constant wire segment placeholder is used instead.

Parameters:

  • ps_dict

    (Dict[int, PortSegment]) –

    The PortSegment dictionary to convert. Each key (int) conforms to the index of the associated PortSegment object.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

set

set(
    port_name: str,
    new_signal: SignalOrLogicLevel,
    idx: Union[int, List[int]] = 0,
) -> None

Sets the signal on a port.

Parameters:

  • port_name

    (str) –

    The name of the port to set the signal on.

  • new_signal

    (Signal) –

    The new signal value.

  • idx

    (Union[int, List[int]], default: 0 ) –

    The index (or indices) to apply the given signal to. Can either be an integer (single index to set) or an iterable of integers (e.g. a list of indices). For every integer of the iterable the signal value of the corresponding port index is set to the given new_signal. Defaults to 0.

Example

from netlist_carpentry.utils.gate_factory import and_gate module = Module(name='m') a = module.create_port('a', 'input', width=6) instance = and_gate(module, 'inst', A=a)

This sets the value of bit 0 of port A to HIGH

instance.set('A', 1, 0) instance.ports['A'].signal_str 'xxxxx1'

This sets the value of bits 1, 3 and 5 of port A to LOW, leaving the other bits as they already are.

instance.set('A', 0, [1, 3, 5]) instance.ports['A'].signal_str '0x0x01'

get_result

get_result(s1: Signal, s2: Signal) -> Signal

Returns the result of this gate's operation for given Signals s1 and s2.

This method is only implemented for bitwise evaluating gates (e.g. AndGate, OrGate). This method raises an UnsupportedOperationError if used on other gates (e.g. Adder).

For vector-level operations on full signal arrays, use :meth:get_result_vector instead.

Parameters:

  • s1

    (Signal) –

    The first Signal, i.e. the first operand.

  • s2

    (Signal) –

    The second Signal, i.e. the second operand.

Raises:

Returns:

  • Signal ( Signal ) –

    The result of this gate's operation on the given signals.

signals_in

signals_in(idx: NonNegativeInt = 0) -> Tuple[Signal, Signal]

The input signals of the gate.

Returns:

signal_out

signal_out(idx: NonNegativeInt = 0) -> Signal

The output signal of the gate.

Returns:

  • Signal ( Signal ) –

    The output signal of the gate.

LessEqual

Bases: BinaryNto1Gate, BaseModel

A LESS-OR-EQUAL gate.

A LESS-OR-EQUAL gate is a gate that produces a HIGH output signal if its "left" input signal value is less or equal to its "right" input signal. Otherwise, it produces a LOW output signal.

Methods:

  • change_mutability

    Change the mutability status of this instance and optionally its ports.

  • evaluate

    Evaluates the gate's output signal based on its input signals.

  • all_connections

    Returns a dictionary mapping port names to their corresponding connection paths.

  • model_post_init

    Initializes the gate's ports and connections.

  • connect

    Add connections to the specified port of this instance.

  • disconnect

    Remove an existing connection from a specified port of this instance.

  • get_connection

    Retrieve the connection path associated with a specified port and bit index.

  • modify_connection

    Modify an existing connection within a specified port of this instance.

  • connect_modify

    Add a new connection or modify an existing one within the specified port of this instance.

  • tie_port

    Set a constant signal value for the specified port and bit index.

  • has_tied_ports

    Checks the ports of this instance whether any are tied to constant values.

  • has_tied_inputs

    Checks the input ports of this instance whether any are tied to constant values.

  • has_tied_outputs

    Checks the output ports of this instance whether any are tied to constant values.

  • update_signedness

    Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

  • split

    Performs a bit-wise split on this instance.

  • p2v

    Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

  • ps2v

    Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

  • set

    Sets the signal on a port.

  • get_result

    Returns the result of this gate's operation for given Signals s1 and s2.

  • signals_in

    The input signals of the gate.

  • signal_out

    The output signal of the gate.

Attributes:

name instance-attribute

name: str

The name of the element.

!!! Do not modify this variable after instantiating it. Use NetlistElement.set_name() instead. Modifying this variable might lead to inconsistencies later on.

metadata class-attribute instance-attribute

Metadata of a netlist element.

Can be user-defined, or e. g. by Yosys (such as src for the HDL source). Is also grouped by categories, i.e. all metadata from Yosys can be accessed via Module.metadata["yosys"], or via Module.metadata.yosys, which both return a dictionary of all metadata. Read the documentation of MetaDataMixin for more information.

path property

Returns the InstancePath of the netlist element.

The InstancePath object is constructed using the element's type and its raw hierarchical path.

Returns:

  • InstancePath ( InstancePath ) –

    The hierarchical path of the netlist element.

type property

type: EType

The type of the element, which is an instance.

hierarchy_level property

hierarchy_level: int

The level of hierarchy of the element in the design.

The hierarchy level is the number of separators in the element's raw path. For example, a top-level instance has a hierarchy level of 0, while a direct submodule instance has a hierarchy level of 1.

Returns:

  • int ( int ) –

    The hierarchy level of the element.

has_parent property

has_parent: bool

Whether this object has a parent.

circuit property

circuit: 'Circuit'

The circuit object to which this netlist element belongs to.

  • For a module, returns the circuit to which the module belongs.
  • For any other netlist element, recursively returns the circuit of the parent, which ultimately leads to a module, to which the netlist element belongs.

Raises:

  • ParentNotFoundError

    If a parent cannot be resolved somewhere in the hierarchical chain.

  • ObjectNotFoundError

    If for a module no circuit is set.

has_circuit property

has_circuit: bool

Whether this netlist element has a defined circuit it belongs to.

Tries to access self.circuit and returns whether the call was successful. Can be used instead of a try-except clause around the call to NetlistElement.circuit.

locked property

locked: bool

True if this NetlistElement instance is locked (i.e. it is currently structurally unchangeable), False if it is mutable.

Can be changed via NetlistElement.change_mutability(bool).

Immutability is used to prevent accidental changes to the design.

is_placeholder_instance property

is_placeholder_instance: bool

A placeholder represents an element that does not have a specific path.

True if this NetlistElement instance represents a placeholder, False otherwise.

can_carry_signal property

can_carry_signal: bool

Whether this exact object is able to receive, pass or hold signal values.

True for ports (as they drive or receive values) and wires (as they pass the signals from driver to load ports) as well as their respective segments. False for instances and modules.

connections property

connections: Dict[str, Dict[int, WireSegmentPath]]

A dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port. Elements with no connection (i.e. the path is None) are excluded. In case these are needed, use Instance.get_connections() instead.

Example

{ 'port1': {1: WireSegmentPath('path/to/element1'), 2: WireSegmentPath('path/to/element2')}, 'port2': {1: WireSegmentPath('path/to/element3')} }

connection_str_paths property

connection_str_paths: Dict[str, Dict[int, str]]

Returns a dictionary mapping port names to their corresponding connection paths as strings.

The keys are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are the raw string paths.

Example

{ 'port1': {0: 'path.to.element1', 1: 'path.to.element2'}, 'port2': {0: 'path.to.element3'} }

ports property

A dictionary mapping port names to their corresponding Port objects.

The keys of the dictionary are the names of the ports. The values are Port objects representing the ports.

Returns:

input_ports property

input_ports: Tuple[Port[Instance], Port[Instance]]

The input ports of the gate as a 2-tuple.

output_ports property

output_ports: Tuple[Port[Instance], ...]

Returns a tuple of output ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as outputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the output ports.

has_unconnected_port_segments property

has_unconnected_port_segments: bool

Returns True if the instance has at least one unconnected port segment.

signals property

signals: Dict[str, SignalArray]

A dictionary with all signals currently present on all ports of this instance.

is_blackbox property

is_blackbox: bool

Flag indicating whether the instance represents neither a primitive element nor a module instance.

If True, this instance does not have a module definition, and is also not a basic component (i.e. a primitive gate instance) from the internal gate library, such as a gate or flip-flop.

y_width property

y_width: PositiveInt

Width of the gate, which is always 1 for gates that reduce N-bit inputs to 1 bit.

a_width property

a_width: PositiveInt

Width of the gate's A port.

b_width property

b_width: PositiveInt

Width of the gate's B port.

is_combinational property

is_combinational: bool

Whether instances of this gate are considered combinational gates.

True for combinational gates, such as AND gates or arithmetic gates. False for flip-flops and latches.

is_sequential property

is_sequential: bool

Whether instances of this gate are considered sequential gates.

False for combinational gates, such as AND gates or arithmetic gates. True for flip-flops and latches.

output_port property

output_port: Port[Instance]

The output port of the gate.

data_width property

data_width: int

The data width of this instance.

Defaults to the data width of the output port. Can be overwritten in extended classes.

In contrast to self.width, which is used for the creation and initialization, this property is linked to the data width of the output port. This property is useful when the data width of the output port can be changed.

a_signed property

a_signed: bool

The signedness of input port A.

b_signed property

b_signed: bool

The signedness of input port B.

truth_table property

truth_table: Dict[Tuple[Signal, Signal], Signal]

A simple truth table as a dictionary.

This dictionary contains the input-output mapping for unary gates that evaluate bitwise (e.g. AndGate, OrGate). Not implemented for arithmetic gates (e.g. Adder).

change_mutability

change_mutability(is_now_locked: bool, recursive: bool = False) -> Self

Change the mutability status of this instance and optionally its ports.

This method allows setting whether this instance can be modified or not. If recursive is set to True, it also applies the same mutability status to all ports of this instance.

Parameters:

  • is_now_locked

    (bool) –

    The new mutability status for this instance.

  • recursive

    (bool, default: False ) –

    Whether to apply the change recursively to its ports. Defaults to False.

evaluate

evaluate() -> None

Evaluates the gate's output signal based on its input signals.

This method is called when the gate's input signals change, and it updates the gate's output signal accordingly.

all_connections

all_connections(
    include_unconnected: bool,
) -> Dict[str, Dict[int, WireSegmentPath]]

Returns a dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port.

Parameters:

  • include_unconnected

    (bool) –

    Whether to include unconnected ports in the result.

Returns:

model_post_init

model_post_init(__context: object) -> None

Initializes the gate's ports and connections.

This method is called after the gate's attributes have been initialized, and it sets up the gate's ports and connections.

connect

connect(
    port_name: str,
    ws_path: Optional[WireSegmentPath],
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add connections to the specified port of this instance.

This method can establish multiple connections if a range of indices is provided.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection(s) should be established.

  • ws_path

    (Optional[WireSegmentPath]) –

    The path of the wire segment that will be connected to this port. If None, the associated port (segment) remains unconnected.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

Raises:

  • ObjectLockedError

    If this instance is currently locked, and no connection can be made.

disconnect

disconnect(port_name: str, index: Optional[int] = None) -> None

Remove an existing connection from a specified port of this instance.

This method disconnects the wire segment at the given index within the specified port_name.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be removed.

  • index

    (Optional[int], default: None ) –

    The bit index within the port for this disconnection. Defaults to None, which completely disconnects the port.

Raises:

get_connection

get_connection(
    port_name: str, index: Optional[NonNegativeInt] = None
) -> Union[WireSegmentPath, Dict[int, WireSegmentPath], None]

Retrieve the connection path associated with a specified port and bit index.

If index is provided, this method returns the wire segment path connected to that specific bit within the port. Otherwise, it returns all connections for the given port as a dictionary mapping indices to WireSegmentPaths.

Parameters:

  • port_name

    (str) –

    The name of the port for which to retrieve the connection(s).

  • index

    (Optional[NonNegativeInt], default: None ) –

    The bit index within the port. Defaults to None.

Returns:

modify_connection

modify_connection(
    port_name: str, ws_path: WireSegmentPath, index: NonNegativeInt = 0
) -> None

Modify an existing connection within a specified port of this instance.

This method updates the wire segment path at the given index within the specified port_name. If the index does not exist yet, it is newly added, changing the width of the port.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be modified.

  • ws_path

    (WireSegmentPath) –

    The new wire segment path for this connection.

  • index

    (NonNegativeInt, default: 0 ) –

    The bit index within the port. Defaults to 0.

connect_modify

connect_modify(
    port_name: str,
    ws_path: WireSegmentPath,
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add a new connection or modify an existing one within the specified port of this instance.

If the connection already exists at the given index and port_name, it will be modified. Otherwise, a new connection is added.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be established or updated.

  • ws_path

    (WireSegmentPath) –

    The path of the wire segment that will be connected to this port.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

tie_port

tie_port(name: str, index: NonNegativeInt, sig_value: LogicLevel) -> None

Set a constant signal value for the specified port and bit index.

If the specified port does not exist, an error message is logged and the function returns False. Otherwise, the method tries to set the constant signal value for that port and returns True if successful.

Does not work for instance output ports, as they are always driven by their parent instances.

Parameters:

  • name

    (str) –

    The name of the port.

  • index

    (NonNegativeInt) –

    The bit index within the port.

  • sig_value

    (LogicLevel) –

    The constant signal value to be set ('0', '1', or 'Z').

Raises:

  • ObjectNotFoundError

    If no such port or port segment exists.

  • AlreadyConnectedError

    (raised by: PortSegment.tie_signal) If this segment is belongs to a load port and is already connected to a wire, from which it receives its value.

  • InvalidDirectionError

    (raised by: PortSegment.tie_signal) If this port segment belongs to an instance output port, which is driven by the instance inputs and the instance's internal logic.

  • InvalidSignalError

    (raised by: PortSegment.tie_signal) If an invalid value is provided.

has_tied_ports

has_tied_ports() -> bool

Checks the ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any ports of this instance are tied to constant values. False otherwise, i.e. all ports are connected to wires.

has_tied_inputs

has_tied_inputs() -> bool

Checks the input ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any input ports of this instance are tied to constant values. False otherwise, i.e. all input ports are connected to wires.

has_tied_outputs

has_tied_outputs() -> bool

Checks the output ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any output ports of this instance are tied to constant values. False otherwise, i.e. all output ports are connected to wires.

update_signedness

update_signedness(port_name: str) -> None

Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

Parameters:

  • port_name

    (str) –

    The name of the port, of which the signedness value is retrieved.

split

split() -> Dict[NonNegativeInt, Self]

Performs a bit-wise split on this instance.

If this instance supports splitting and has a data width of n bit, this method splits this instance into n 1-bit instances. This works for instances, where each output bit depends only on the corresponding input bit(s), e.g. an AND gate or a D-Flipflop.

Returns:

  • Dict[NonNegativeInt, Self]

    Dict[int, Instance]: An n-bit large dictionary, where each key conforms to a bit of the original instance, and each value is an 1-bit instance representing the corresponding "slice" of the original instance.

Raises:

  • SplittingUnsupportedError

    If this instance does not support splitting. Happens for any gate or instance whose behavior depends on the whole bus, and splitting would make it lose its meaning.

p2v

p2v(
    port: ANY_PORT,
    exclude_indices: Optional[List[int]] = None,
    include_indices: Optional[List[int]] = None,
) -> str

Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a Port object and converts them to their corresponding Verilog signal structure (p2v -> Port to Verilog signal syntax). For each segment of the port, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port is set to a constant, the corresponding constant wire segment placeholder is used instead. Port segments can be excluded from the conversion by providing a list of indices to the exclude_indices parameter, indicating which segments should be excluded from the conversion (e.g. segments that are known to be unconnected). Vice versa, only a certain subset of the port's segments may be converted to Verilog syntax, if include_indices is a given list of port indices. All indices not present in the list will be excluded from the conversion.

Parameters:

  • port

    (Port) –

    The Port object to convert.

  • exclude_indices

    (List[int], default: None ) –

    A list of indices to exclude from the conversion. Defaults to None.

  • include_indices

    (List[int], default: None ) –

    A list of indices (i.e. port slices) to include only for the conversion. Defaults to None.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

  • ObjectNotFoundError

    If the wire connected to a certain port segment could not be found.

  • UnsupportedOperationError

    If both exclude_indices and include_indices are specified. Only one of both may be given when calling this method.

ps2v

Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a PortSegment dictionary and converts them to their corresponding Verilog signal structure (ps2v -> PortSegment to Verilog signal syntax). For each segment, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port segment is set to a constant, the corresponding constant wire segment placeholder is used instead.

Parameters:

  • ps_dict

    (Dict[int, PortSegment]) –

    The PortSegment dictionary to convert. Each key (int) conforms to the index of the associated PortSegment object.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

set

set(
    port_name: str,
    new_signal: SignalOrLogicLevel,
    idx: Union[int, List[int]] = 0,
) -> None

Sets the signal on a port.

Parameters:

  • port_name

    (str) –

    The name of the port to set the signal on.

  • new_signal

    (Signal) –

    The new signal value.

  • idx

    (Union[int, List[int]], default: 0 ) –

    The index (or indices) to apply the given signal to. Can either be an integer (single index to set) or an iterable of integers (e.g. a list of indices). For every integer of the iterable the signal value of the corresponding port index is set to the given new_signal. Defaults to 0.

Example

from netlist_carpentry.utils.gate_factory import and_gate module = Module(name='m') a = module.create_port('a', 'input', width=6) instance = and_gate(module, 'inst', A=a)

This sets the value of bit 0 of port A to HIGH

instance.set('A', 1, 0) instance.ports['A'].signal_str 'xxxxx1'

This sets the value of bits 1, 3 and 5 of port A to LOW, leaving the other bits as they already are.

instance.set('A', 0, [1, 3, 5]) instance.ports['A'].signal_str '0x0x01'

get_result

get_result(s1: Signal, s2: Signal) -> Signal

Returns the result of this gate's operation for given Signals s1 and s2.

This method is only implemented for bitwise evaluating gates (e.g. AndGate, OrGate). This method raises an UnsupportedOperationError if used on other gates (e.g. Adder).

For vector-level operations on full signal arrays, use :meth:get_result_vector instead.

Parameters:

  • s1

    (Signal) –

    The first Signal, i.e. the first operand.

  • s2

    (Signal) –

    The second Signal, i.e. the second operand.

Raises:

Returns:

  • Signal ( Signal ) –

    The result of this gate's operation on the given signals.

signals_in

signals_in(idx: NonNegativeInt = 0) -> Tuple[Signal, Signal]

The input signals of the gate.

Returns:

signal_out

signal_out(idx: NonNegativeInt = 0) -> Signal

The output signal of the gate.

Returns:

  • Signal ( Signal ) –

    The output signal of the gate.

Equal

Bases: BinaryNto1Gate, BaseModel

An EQUAL gate.

An EQUAL gate is a gate that produces a HIGH output signal only if both input signals have the same value. Otherwise, it produces a LOW output signal. Produces UNDEFINED, if one of the input signals is x or z.

Methods:

  • change_mutability

    Change the mutability status of this instance and optionally its ports.

  • evaluate

    Evaluates the gate's output signal based on its input signals.

  • all_connections

    Returns a dictionary mapping port names to their corresponding connection paths.

  • model_post_init

    Initializes the gate's ports and connections.

  • connect

    Add connections to the specified port of this instance.

  • disconnect

    Remove an existing connection from a specified port of this instance.

  • get_connection

    Retrieve the connection path associated with a specified port and bit index.

  • modify_connection

    Modify an existing connection within a specified port of this instance.

  • connect_modify

    Add a new connection or modify an existing one within the specified port of this instance.

  • tie_port

    Set a constant signal value for the specified port and bit index.

  • has_tied_ports

    Checks the ports of this instance whether any are tied to constant values.

  • has_tied_inputs

    Checks the input ports of this instance whether any are tied to constant values.

  • has_tied_outputs

    Checks the output ports of this instance whether any are tied to constant values.

  • update_signedness

    Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

  • split

    Performs a bit-wise split on this instance.

  • p2v

    Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

  • ps2v

    Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

  • set

    Sets the signal on a port.

  • get_result

    Returns the result of this gate's operation for given Signals s1 and s2.

  • signals_in

    The input signals of the gate.

  • signal_out

    The output signal of the gate.

Attributes:

name instance-attribute

name: str

The name of the element.

!!! Do not modify this variable after instantiating it. Use NetlistElement.set_name() instead. Modifying this variable might lead to inconsistencies later on.

metadata class-attribute instance-attribute

Metadata of a netlist element.

Can be user-defined, or e. g. by Yosys (such as src for the HDL source). Is also grouped by categories, i.e. all metadata from Yosys can be accessed via Module.metadata["yosys"], or via Module.metadata.yosys, which both return a dictionary of all metadata. Read the documentation of MetaDataMixin for more information.

path property

Returns the InstancePath of the netlist element.

The InstancePath object is constructed using the element's type and its raw hierarchical path.

Returns:

  • InstancePath ( InstancePath ) –

    The hierarchical path of the netlist element.

type property

type: EType

The type of the element, which is an instance.

hierarchy_level property

hierarchy_level: int

The level of hierarchy of the element in the design.

The hierarchy level is the number of separators in the element's raw path. For example, a top-level instance has a hierarchy level of 0, while a direct submodule instance has a hierarchy level of 1.

Returns:

  • int ( int ) –

    The hierarchy level of the element.

has_parent property

has_parent: bool

Whether this object has a parent.

circuit property

circuit: 'Circuit'

The circuit object to which this netlist element belongs to.

  • For a module, returns the circuit to which the module belongs.
  • For any other netlist element, recursively returns the circuit of the parent, which ultimately leads to a module, to which the netlist element belongs.

Raises:

  • ParentNotFoundError

    If a parent cannot be resolved somewhere in the hierarchical chain.

  • ObjectNotFoundError

    If for a module no circuit is set.

has_circuit property

has_circuit: bool

Whether this netlist element has a defined circuit it belongs to.

Tries to access self.circuit and returns whether the call was successful. Can be used instead of a try-except clause around the call to NetlistElement.circuit.

locked property

locked: bool

True if this NetlistElement instance is locked (i.e. it is currently structurally unchangeable), False if it is mutable.

Can be changed via NetlistElement.change_mutability(bool).

Immutability is used to prevent accidental changes to the design.

is_placeholder_instance property

is_placeholder_instance: bool

A placeholder represents an element that does not have a specific path.

True if this NetlistElement instance represents a placeholder, False otherwise.

can_carry_signal property

can_carry_signal: bool

Whether this exact object is able to receive, pass or hold signal values.

True for ports (as they drive or receive values) and wires (as they pass the signals from driver to load ports) as well as their respective segments. False for instances and modules.

connections property

connections: Dict[str, Dict[int, WireSegmentPath]]

A dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port. Elements with no connection (i.e. the path is None) are excluded. In case these are needed, use Instance.get_connections() instead.

Example

{ 'port1': {1: WireSegmentPath('path/to/element1'), 2: WireSegmentPath('path/to/element2')}, 'port2': {1: WireSegmentPath('path/to/element3')} }

connection_str_paths property

connection_str_paths: Dict[str, Dict[int, str]]

Returns a dictionary mapping port names to their corresponding connection paths as strings.

The keys are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are the raw string paths.

Example

{ 'port1': {0: 'path.to.element1', 1: 'path.to.element2'}, 'port2': {0: 'path.to.element3'} }

ports property

A dictionary mapping port names to their corresponding Port objects.

The keys of the dictionary are the names of the ports. The values are Port objects representing the ports.

Returns:

input_ports property

input_ports: Tuple[Port[Instance], Port[Instance]]

The input ports of the gate as a 2-tuple.

output_ports property

output_ports: Tuple[Port[Instance], ...]

Returns a tuple of output ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as outputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the output ports.

has_unconnected_port_segments property

has_unconnected_port_segments: bool

Returns True if the instance has at least one unconnected port segment.

signals property

signals: Dict[str, SignalArray]

A dictionary with all signals currently present on all ports of this instance.

is_blackbox property

is_blackbox: bool

Flag indicating whether the instance represents neither a primitive element nor a module instance.

If True, this instance does not have a module definition, and is also not a basic component (i.e. a primitive gate instance) from the internal gate library, such as a gate or flip-flop.

y_width property

y_width: PositiveInt

Width of the gate, which is always 1 for gates that reduce N-bit inputs to 1 bit.

a_width property

a_width: PositiveInt

Width of the gate's A port.

b_width property

b_width: PositiveInt

Width of the gate's B port.

is_combinational property

is_combinational: bool

Whether instances of this gate are considered combinational gates.

True for combinational gates, such as AND gates or arithmetic gates. False for flip-flops and latches.

is_sequential property

is_sequential: bool

Whether instances of this gate are considered sequential gates.

False for combinational gates, such as AND gates or arithmetic gates. True for flip-flops and latches.

output_port property

output_port: Port[Instance]

The output port of the gate.

data_width property

data_width: int

The data width of this instance.

Defaults to the data width of the output port. Can be overwritten in extended classes.

In contrast to self.width, which is used for the creation and initialization, this property is linked to the data width of the output port. This property is useful when the data width of the output port can be changed.

a_signed property

a_signed: bool

The signedness of input port A.

b_signed property

b_signed: bool

The signedness of input port B.

truth_table property

truth_table: Dict[Tuple[Signal, Signal], Signal]

A simple truth table as a dictionary.

This dictionary contains the input-output mapping for unary gates that evaluate bitwise (e.g. AndGate, OrGate). Not implemented for arithmetic gates (e.g. Adder).

change_mutability

change_mutability(is_now_locked: bool, recursive: bool = False) -> Self

Change the mutability status of this instance and optionally its ports.

This method allows setting whether this instance can be modified or not. If recursive is set to True, it also applies the same mutability status to all ports of this instance.

Parameters:

  • is_now_locked

    (bool) –

    The new mutability status for this instance.

  • recursive

    (bool, default: False ) –

    Whether to apply the change recursively to its ports. Defaults to False.

evaluate

evaluate() -> None

Evaluates the gate's output signal based on its input signals.

This method is called when the gate's input signals change, and it updates the gate's output signal accordingly.

all_connections

all_connections(
    include_unconnected: bool,
) -> Dict[str, Dict[int, WireSegmentPath]]

Returns a dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port.

Parameters:

  • include_unconnected

    (bool) –

    Whether to include unconnected ports in the result.

Returns:

model_post_init

model_post_init(__context: object) -> None

Initializes the gate's ports and connections.

This method is called after the gate's attributes have been initialized, and it sets up the gate's ports and connections.

connect

connect(
    port_name: str,
    ws_path: Optional[WireSegmentPath],
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add connections to the specified port of this instance.

This method can establish multiple connections if a range of indices is provided.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection(s) should be established.

  • ws_path

    (Optional[WireSegmentPath]) –

    The path of the wire segment that will be connected to this port. If None, the associated port (segment) remains unconnected.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

Raises:

  • ObjectLockedError

    If this instance is currently locked, and no connection can be made.

disconnect

disconnect(port_name: str, index: Optional[int] = None) -> None

Remove an existing connection from a specified port of this instance.

This method disconnects the wire segment at the given index within the specified port_name.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be removed.

  • index

    (Optional[int], default: None ) –

    The bit index within the port for this disconnection. Defaults to None, which completely disconnects the port.

Raises:

get_connection

get_connection(
    port_name: str, index: Optional[NonNegativeInt] = None
) -> Union[WireSegmentPath, Dict[int, WireSegmentPath], None]

Retrieve the connection path associated with a specified port and bit index.

If index is provided, this method returns the wire segment path connected to that specific bit within the port. Otherwise, it returns all connections for the given port as a dictionary mapping indices to WireSegmentPaths.

Parameters:

  • port_name

    (str) –

    The name of the port for which to retrieve the connection(s).

  • index

    (Optional[NonNegativeInt], default: None ) –

    The bit index within the port. Defaults to None.

Returns:

modify_connection

modify_connection(
    port_name: str, ws_path: WireSegmentPath, index: NonNegativeInt = 0
) -> None

Modify an existing connection within a specified port of this instance.

This method updates the wire segment path at the given index within the specified port_name. If the index does not exist yet, it is newly added, changing the width of the port.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be modified.

  • ws_path

    (WireSegmentPath) –

    The new wire segment path for this connection.

  • index

    (NonNegativeInt, default: 0 ) –

    The bit index within the port. Defaults to 0.

connect_modify

connect_modify(
    port_name: str,
    ws_path: WireSegmentPath,
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add a new connection or modify an existing one within the specified port of this instance.

If the connection already exists at the given index and port_name, it will be modified. Otherwise, a new connection is added.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be established or updated.

  • ws_path

    (WireSegmentPath) –

    The path of the wire segment that will be connected to this port.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

tie_port

tie_port(name: str, index: NonNegativeInt, sig_value: LogicLevel) -> None

Set a constant signal value for the specified port and bit index.

If the specified port does not exist, an error message is logged and the function returns False. Otherwise, the method tries to set the constant signal value for that port and returns True if successful.

Does not work for instance output ports, as they are always driven by their parent instances.

Parameters:

  • name

    (str) –

    The name of the port.

  • index

    (NonNegativeInt) –

    The bit index within the port.

  • sig_value

    (LogicLevel) –

    The constant signal value to be set ('0', '1', or 'Z').

Raises:

  • ObjectNotFoundError

    If no such port or port segment exists.

  • AlreadyConnectedError

    (raised by: PortSegment.tie_signal) If this segment is belongs to a load port and is already connected to a wire, from which it receives its value.

  • InvalidDirectionError

    (raised by: PortSegment.tie_signal) If this port segment belongs to an instance output port, which is driven by the instance inputs and the instance's internal logic.

  • InvalidSignalError

    (raised by: PortSegment.tie_signal) If an invalid value is provided.

has_tied_ports

has_tied_ports() -> bool

Checks the ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any ports of this instance are tied to constant values. False otherwise, i.e. all ports are connected to wires.

has_tied_inputs

has_tied_inputs() -> bool

Checks the input ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any input ports of this instance are tied to constant values. False otherwise, i.e. all input ports are connected to wires.

has_tied_outputs

has_tied_outputs() -> bool

Checks the output ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any output ports of this instance are tied to constant values. False otherwise, i.e. all output ports are connected to wires.

update_signedness

update_signedness(port_name: str) -> None

Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

Parameters:

  • port_name

    (str) –

    The name of the port, of which the signedness value is retrieved.

split

split() -> Dict[NonNegativeInt, Self]

Performs a bit-wise split on this instance.

If this instance supports splitting and has a data width of n bit, this method splits this instance into n 1-bit instances. This works for instances, where each output bit depends only on the corresponding input bit(s), e.g. an AND gate or a D-Flipflop.

Returns:

  • Dict[NonNegativeInt, Self]

    Dict[int, Instance]: An n-bit large dictionary, where each key conforms to a bit of the original instance, and each value is an 1-bit instance representing the corresponding "slice" of the original instance.

Raises:

  • SplittingUnsupportedError

    If this instance does not support splitting. Happens for any gate or instance whose behavior depends on the whole bus, and splitting would make it lose its meaning.

p2v

p2v(
    port: ANY_PORT,
    exclude_indices: Optional[List[int]] = None,
    include_indices: Optional[List[int]] = None,
) -> str

Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a Port object and converts them to their corresponding Verilog signal structure (p2v -> Port to Verilog signal syntax). For each segment of the port, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port is set to a constant, the corresponding constant wire segment placeholder is used instead. Port segments can be excluded from the conversion by providing a list of indices to the exclude_indices parameter, indicating which segments should be excluded from the conversion (e.g. segments that are known to be unconnected). Vice versa, only a certain subset of the port's segments may be converted to Verilog syntax, if include_indices is a given list of port indices. All indices not present in the list will be excluded from the conversion.

Parameters:

  • port

    (Port) –

    The Port object to convert.

  • exclude_indices

    (List[int], default: None ) –

    A list of indices to exclude from the conversion. Defaults to None.

  • include_indices

    (List[int], default: None ) –

    A list of indices (i.e. port slices) to include only for the conversion. Defaults to None.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

  • ObjectNotFoundError

    If the wire connected to a certain port segment could not be found.

  • UnsupportedOperationError

    If both exclude_indices and include_indices are specified. Only one of both may be given when calling this method.

ps2v

Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a PortSegment dictionary and converts them to their corresponding Verilog signal structure (ps2v -> PortSegment to Verilog signal syntax). For each segment, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port segment is set to a constant, the corresponding constant wire segment placeholder is used instead.

Parameters:

  • ps_dict

    (Dict[int, PortSegment]) –

    The PortSegment dictionary to convert. Each key (int) conforms to the index of the associated PortSegment object.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

set

set(
    port_name: str,
    new_signal: SignalOrLogicLevel,
    idx: Union[int, List[int]] = 0,
) -> None

Sets the signal on a port.

Parameters:

  • port_name

    (str) –

    The name of the port to set the signal on.

  • new_signal

    (Signal) –

    The new signal value.

  • idx

    (Union[int, List[int]], default: 0 ) –

    The index (or indices) to apply the given signal to. Can either be an integer (single index to set) or an iterable of integers (e.g. a list of indices). For every integer of the iterable the signal value of the corresponding port index is set to the given new_signal. Defaults to 0.

Example

from netlist_carpentry.utils.gate_factory import and_gate module = Module(name='m') a = module.create_port('a', 'input', width=6) instance = and_gate(module, 'inst', A=a)

This sets the value of bit 0 of port A to HIGH

instance.set('A', 1, 0) instance.ports['A'].signal_str 'xxxxx1'

This sets the value of bits 1, 3 and 5 of port A to LOW, leaving the other bits as they already are.

instance.set('A', 0, [1, 3, 5]) instance.ports['A'].signal_str '0x0x01'

get_result

get_result(s1: Signal, s2: Signal) -> Signal

Returns the result of this gate's operation for given Signals s1 and s2.

This method is only implemented for bitwise evaluating gates (e.g. AndGate, OrGate). This method raises an UnsupportedOperationError if used on other gates (e.g. Adder).

For vector-level operations on full signal arrays, use :meth:get_result_vector instead.

Parameters:

  • s1

    (Signal) –

    The first Signal, i.e. the first operand.

  • s2

    (Signal) –

    The second Signal, i.e. the second operand.

Raises:

Returns:

  • Signal ( Signal ) –

    The result of this gate's operation on the given signals.

signals_in

signals_in(idx: NonNegativeInt = 0) -> Tuple[Signal, Signal]

The input signals of the gate.

Returns:

signal_out

signal_out(idx: NonNegativeInt = 0) -> Signal

The output signal of the gate.

Returns:

  • Signal ( Signal ) –

    The output signal of the gate.

CaseEqual

Bases: BinaryNto1Gate, BaseModel

A CASE-EQUAL gate.

A CASE-EQUAL gate is a gate that produces a HIGH output signal only if both input signals have the same value. Otherwise, it produces a LOW output signal.

Unlike the normal equality comparison (Equal gate, §eq) that can give x as output, this gate produces an exact equality comparison. It will strictly give 0 or 1 as output, even if input includes x or z values, implementing the Verilog === operator.

Methods:

  • change_mutability

    Change the mutability status of this instance and optionally its ports.

  • evaluate

    Evaluates the gate's output signal based on its input signals.

  • all_connections

    Returns a dictionary mapping port names to their corresponding connection paths.

  • model_post_init

    Initializes the gate's ports and connections.

  • connect

    Add connections to the specified port of this instance.

  • disconnect

    Remove an existing connection from a specified port of this instance.

  • get_connection

    Retrieve the connection path associated with a specified port and bit index.

  • modify_connection

    Modify an existing connection within a specified port of this instance.

  • connect_modify

    Add a new connection or modify an existing one within the specified port of this instance.

  • tie_port

    Set a constant signal value for the specified port and bit index.

  • has_tied_ports

    Checks the ports of this instance whether any are tied to constant values.

  • has_tied_inputs

    Checks the input ports of this instance whether any are tied to constant values.

  • has_tied_outputs

    Checks the output ports of this instance whether any are tied to constant values.

  • update_signedness

    Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

  • split

    Performs a bit-wise split on this instance.

  • p2v

    Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

  • ps2v

    Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

  • set

    Sets the signal on a port.

  • get_result

    Returns the result of this gate's operation for given Signals s1 and s2.

  • signals_in

    The input signals of the gate.

  • signal_out

    The output signal of the gate.

Attributes:

name instance-attribute

name: str

The name of the element.

!!! Do not modify this variable after instantiating it. Use NetlistElement.set_name() instead. Modifying this variable might lead to inconsistencies later on.

metadata class-attribute instance-attribute

Metadata of a netlist element.

Can be user-defined, or e. g. by Yosys (such as src for the HDL source). Is also grouped by categories, i.e. all metadata from Yosys can be accessed via Module.metadata["yosys"], or via Module.metadata.yosys, which both return a dictionary of all metadata. Read the documentation of MetaDataMixin for more information.

path property

Returns the InstancePath of the netlist element.

The InstancePath object is constructed using the element's type and its raw hierarchical path.

Returns:

  • InstancePath ( InstancePath ) –

    The hierarchical path of the netlist element.

type property

type: EType

The type of the element, which is an instance.

hierarchy_level property

hierarchy_level: int

The level of hierarchy of the element in the design.

The hierarchy level is the number of separators in the element's raw path. For example, a top-level instance has a hierarchy level of 0, while a direct submodule instance has a hierarchy level of 1.

Returns:

  • int ( int ) –

    The hierarchy level of the element.

has_parent property

has_parent: bool

Whether this object has a parent.

circuit property

circuit: 'Circuit'

The circuit object to which this netlist element belongs to.

  • For a module, returns the circuit to which the module belongs.
  • For any other netlist element, recursively returns the circuit of the parent, which ultimately leads to a module, to which the netlist element belongs.

Raises:

  • ParentNotFoundError

    If a parent cannot be resolved somewhere in the hierarchical chain.

  • ObjectNotFoundError

    If for a module no circuit is set.

has_circuit property

has_circuit: bool

Whether this netlist element has a defined circuit it belongs to.

Tries to access self.circuit and returns whether the call was successful. Can be used instead of a try-except clause around the call to NetlistElement.circuit.

locked property

locked: bool

True if this NetlistElement instance is locked (i.e. it is currently structurally unchangeable), False if it is mutable.

Can be changed via NetlistElement.change_mutability(bool).

Immutability is used to prevent accidental changes to the design.

is_placeholder_instance property

is_placeholder_instance: bool

A placeholder represents an element that does not have a specific path.

True if this NetlistElement instance represents a placeholder, False otherwise.

can_carry_signal property

can_carry_signal: bool

Whether this exact object is able to receive, pass or hold signal values.

True for ports (as they drive or receive values) and wires (as they pass the signals from driver to load ports) as well as their respective segments. False for instances and modules.

connections property

connections: Dict[str, Dict[int, WireSegmentPath]]

A dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port. Elements with no connection (i.e. the path is None) are excluded. In case these are needed, use Instance.get_connections() instead.

Example

{ 'port1': {1: WireSegmentPath('path/to/element1'), 2: WireSegmentPath('path/to/element2')}, 'port2': {1: WireSegmentPath('path/to/element3')} }

connection_str_paths property

connection_str_paths: Dict[str, Dict[int, str]]

Returns a dictionary mapping port names to their corresponding connection paths as strings.

The keys are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are the raw string paths.

Example

{ 'port1': {0: 'path.to.element1', 1: 'path.to.element2'}, 'port2': {0: 'path.to.element3'} }

ports property

A dictionary mapping port names to their corresponding Port objects.

The keys of the dictionary are the names of the ports. The values are Port objects representing the ports.

Returns:

input_ports property

input_ports: Tuple[Port[Instance], Port[Instance]]

The input ports of the gate as a 2-tuple.

output_ports property

output_ports: Tuple[Port[Instance], ...]

Returns a tuple of output ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as outputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the output ports.

has_unconnected_port_segments property

has_unconnected_port_segments: bool

Returns True if the instance has at least one unconnected port segment.

signals property

signals: Dict[str, SignalArray]

A dictionary with all signals currently present on all ports of this instance.

is_blackbox property

is_blackbox: bool

Flag indicating whether the instance represents neither a primitive element nor a module instance.

If True, this instance does not have a module definition, and is also not a basic component (i.e. a primitive gate instance) from the internal gate library, such as a gate or flip-flop.

y_width property

y_width: PositiveInt

Width of the gate, which is always 1 for gates that reduce N-bit inputs to 1 bit.

a_width property

a_width: PositiveInt

Width of the gate's A port.

b_width property

b_width: PositiveInt

Width of the gate's B port.

is_combinational property

is_combinational: bool

Whether instances of this gate are considered combinational gates.

True for combinational gates, such as AND gates or arithmetic gates. False for flip-flops and latches.

is_sequential property

is_sequential: bool

Whether instances of this gate are considered sequential gates.

False for combinational gates, such as AND gates or arithmetic gates. True for flip-flops and latches.

output_port property

output_port: Port[Instance]

The output port of the gate.

data_width property

data_width: int

The data width of this instance.

Defaults to the data width of the output port. Can be overwritten in extended classes.

In contrast to self.width, which is used for the creation and initialization, this property is linked to the data width of the output port. This property is useful when the data width of the output port can be changed.

a_signed property

a_signed: bool

The signedness of input port A.

b_signed property

b_signed: bool

The signedness of input port B.

truth_table property

truth_table: Dict[Tuple[Signal, Signal], Signal]

A simple truth table as a dictionary.

This dictionary contains the input-output mapping for unary gates that evaluate bitwise (e.g. AndGate, OrGate). Not implemented for arithmetic gates (e.g. Adder).

change_mutability

change_mutability(is_now_locked: bool, recursive: bool = False) -> Self

Change the mutability status of this instance and optionally its ports.

This method allows setting whether this instance can be modified or not. If recursive is set to True, it also applies the same mutability status to all ports of this instance.

Parameters:

  • is_now_locked

    (bool) –

    The new mutability status for this instance.

  • recursive

    (bool, default: False ) –

    Whether to apply the change recursively to its ports. Defaults to False.

evaluate

evaluate() -> None

Evaluates the gate's output signal based on its input signals.

This method is called when the gate's input signals change, and it updates the gate's output signal accordingly.

all_connections

all_connections(
    include_unconnected: bool,
) -> Dict[str, Dict[int, WireSegmentPath]]

Returns a dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port.

Parameters:

  • include_unconnected

    (bool) –

    Whether to include unconnected ports in the result.

Returns:

model_post_init

model_post_init(__context: object) -> None

Initializes the gate's ports and connections.

This method is called after the gate's attributes have been initialized, and it sets up the gate's ports and connections.

connect

connect(
    port_name: str,
    ws_path: Optional[WireSegmentPath],
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add connections to the specified port of this instance.

This method can establish multiple connections if a range of indices is provided.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection(s) should be established.

  • ws_path

    (Optional[WireSegmentPath]) –

    The path of the wire segment that will be connected to this port. If None, the associated port (segment) remains unconnected.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

Raises:

  • ObjectLockedError

    If this instance is currently locked, and no connection can be made.

disconnect

disconnect(port_name: str, index: Optional[int] = None) -> None

Remove an existing connection from a specified port of this instance.

This method disconnects the wire segment at the given index within the specified port_name.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be removed.

  • index

    (Optional[int], default: None ) –

    The bit index within the port for this disconnection. Defaults to None, which completely disconnects the port.

Raises:

get_connection

get_connection(
    port_name: str, index: Optional[NonNegativeInt] = None
) -> Union[WireSegmentPath, Dict[int, WireSegmentPath], None]

Retrieve the connection path associated with a specified port and bit index.

If index is provided, this method returns the wire segment path connected to that specific bit within the port. Otherwise, it returns all connections for the given port as a dictionary mapping indices to WireSegmentPaths.

Parameters:

  • port_name

    (str) –

    The name of the port for which to retrieve the connection(s).

  • index

    (Optional[NonNegativeInt], default: None ) –

    The bit index within the port. Defaults to None.

Returns:

modify_connection

modify_connection(
    port_name: str, ws_path: WireSegmentPath, index: NonNegativeInt = 0
) -> None

Modify an existing connection within a specified port of this instance.

This method updates the wire segment path at the given index within the specified port_name. If the index does not exist yet, it is newly added, changing the width of the port.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be modified.

  • ws_path

    (WireSegmentPath) –

    The new wire segment path for this connection.

  • index

    (NonNegativeInt, default: 0 ) –

    The bit index within the port. Defaults to 0.

connect_modify

connect_modify(
    port_name: str,
    ws_path: WireSegmentPath,
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add a new connection or modify an existing one within the specified port of this instance.

If the connection already exists at the given index and port_name, it will be modified. Otherwise, a new connection is added.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be established or updated.

  • ws_path

    (WireSegmentPath) –

    The path of the wire segment that will be connected to this port.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

tie_port

tie_port(name: str, index: NonNegativeInt, sig_value: LogicLevel) -> None

Set a constant signal value for the specified port and bit index.

If the specified port does not exist, an error message is logged and the function returns False. Otherwise, the method tries to set the constant signal value for that port and returns True if successful.

Does not work for instance output ports, as they are always driven by their parent instances.

Parameters:

  • name

    (str) –

    The name of the port.

  • index

    (NonNegativeInt) –

    The bit index within the port.

  • sig_value

    (LogicLevel) –

    The constant signal value to be set ('0', '1', or 'Z').

Raises:

  • ObjectNotFoundError

    If no such port or port segment exists.

  • AlreadyConnectedError

    (raised by: PortSegment.tie_signal) If this segment is belongs to a load port and is already connected to a wire, from which it receives its value.

  • InvalidDirectionError

    (raised by: PortSegment.tie_signal) If this port segment belongs to an instance output port, which is driven by the instance inputs and the instance's internal logic.

  • InvalidSignalError

    (raised by: PortSegment.tie_signal) If an invalid value is provided.

has_tied_ports

has_tied_ports() -> bool

Checks the ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any ports of this instance are tied to constant values. False otherwise, i.e. all ports are connected to wires.

has_tied_inputs

has_tied_inputs() -> bool

Checks the input ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any input ports of this instance are tied to constant values. False otherwise, i.e. all input ports are connected to wires.

has_tied_outputs

has_tied_outputs() -> bool

Checks the output ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any output ports of this instance are tied to constant values. False otherwise, i.e. all output ports are connected to wires.

update_signedness

update_signedness(port_name: str) -> None

Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

Parameters:

  • port_name

    (str) –

    The name of the port, of which the signedness value is retrieved.

split

split() -> Dict[NonNegativeInt, Self]

Performs a bit-wise split on this instance.

If this instance supports splitting and has a data width of n bit, this method splits this instance into n 1-bit instances. This works for instances, where each output bit depends only on the corresponding input bit(s), e.g. an AND gate or a D-Flipflop.

Returns:

  • Dict[NonNegativeInt, Self]

    Dict[int, Instance]: An n-bit large dictionary, where each key conforms to a bit of the original instance, and each value is an 1-bit instance representing the corresponding "slice" of the original instance.

Raises:

  • SplittingUnsupportedError

    If this instance does not support splitting. Happens for any gate or instance whose behavior depends on the whole bus, and splitting would make it lose its meaning.

p2v

p2v(
    port: ANY_PORT,
    exclude_indices: Optional[List[int]] = None,
    include_indices: Optional[List[int]] = None,
) -> str

Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a Port object and converts them to their corresponding Verilog signal structure (p2v -> Port to Verilog signal syntax). For each segment of the port, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port is set to a constant, the corresponding constant wire segment placeholder is used instead. Port segments can be excluded from the conversion by providing a list of indices to the exclude_indices parameter, indicating which segments should be excluded from the conversion (e.g. segments that are known to be unconnected). Vice versa, only a certain subset of the port's segments may be converted to Verilog syntax, if include_indices is a given list of port indices. All indices not present in the list will be excluded from the conversion.

Parameters:

  • port

    (Port) –

    The Port object to convert.

  • exclude_indices

    (List[int], default: None ) –

    A list of indices to exclude from the conversion. Defaults to None.

  • include_indices

    (List[int], default: None ) –

    A list of indices (i.e. port slices) to include only for the conversion. Defaults to None.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

  • ObjectNotFoundError

    If the wire connected to a certain port segment could not be found.

  • UnsupportedOperationError

    If both exclude_indices and include_indices are specified. Only one of both may be given when calling this method.

ps2v

Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a PortSegment dictionary and converts them to their corresponding Verilog signal structure (ps2v -> PortSegment to Verilog signal syntax). For each segment, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port segment is set to a constant, the corresponding constant wire segment placeholder is used instead.

Parameters:

  • ps_dict

    (Dict[int, PortSegment]) –

    The PortSegment dictionary to convert. Each key (int) conforms to the index of the associated PortSegment object.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

set

set(
    port_name: str,
    new_signal: SignalOrLogicLevel,
    idx: Union[int, List[int]] = 0,
) -> None

Sets the signal on a port.

Parameters:

  • port_name

    (str) –

    The name of the port to set the signal on.

  • new_signal

    (Signal) –

    The new signal value.

  • idx

    (Union[int, List[int]], default: 0 ) –

    The index (or indices) to apply the given signal to. Can either be an integer (single index to set) or an iterable of integers (e.g. a list of indices). For every integer of the iterable the signal value of the corresponding port index is set to the given new_signal. Defaults to 0.

Example

from netlist_carpentry.utils.gate_factory import and_gate module = Module(name='m') a = module.create_port('a', 'input', width=6) instance = and_gate(module, 'inst', A=a)

This sets the value of bit 0 of port A to HIGH

instance.set('A', 1, 0) instance.ports['A'].signal_str 'xxxxx1'

This sets the value of bits 1, 3 and 5 of port A to LOW, leaving the other bits as they already are.

instance.set('A', 0, [1, 3, 5]) instance.ports['A'].signal_str '0x0x01'

get_result

get_result(s1: Signal, s2: Signal) -> Signal

Returns the result of this gate's operation for given Signals s1 and s2.

This method is only implemented for bitwise evaluating gates (e.g. AndGate, OrGate). This method raises an UnsupportedOperationError if used on other gates (e.g. Adder).

For vector-level operations on full signal arrays, use :meth:get_result_vector instead.

Parameters:

  • s1

    (Signal) –

    The first Signal, i.e. the first operand.

  • s2

    (Signal) –

    The second Signal, i.e. the second operand.

Raises:

Returns:

  • Signal ( Signal ) –

    The result of this gate's operation on the given signals.

signals_in

signals_in(idx: NonNegativeInt = 0) -> Tuple[Signal, Signal]

The input signals of the gate.

Returns:

signal_out

signal_out(idx: NonNegativeInt = 0) -> Signal

The output signal of the gate.

Returns:

  • Signal ( Signal ) –

    The output signal of the gate.

NotEqual

Bases: BinaryNto1Gate, BaseModel

A NOT-EQUAL gate.

A NOT-EQUAL gate is a gate that produces a HIGH output signal only if both input signals have different values. Otherwise (if both are equal), it produces a LOW output signal. Produces UNDEFINED, if one of the input signals is x or z.

Methods:

  • change_mutability

    Change the mutability status of this instance and optionally its ports.

  • evaluate

    Evaluates the gate's output signal based on its input signals.

  • all_connections

    Returns a dictionary mapping port names to their corresponding connection paths.

  • model_post_init

    Initializes the gate's ports and connections.

  • connect

    Add connections to the specified port of this instance.

  • disconnect

    Remove an existing connection from a specified port of this instance.

  • get_connection

    Retrieve the connection path associated with a specified port and bit index.

  • modify_connection

    Modify an existing connection within a specified port of this instance.

  • connect_modify

    Add a new connection or modify an existing one within the specified port of this instance.

  • tie_port

    Set a constant signal value for the specified port and bit index.

  • has_tied_ports

    Checks the ports of this instance whether any are tied to constant values.

  • has_tied_inputs

    Checks the input ports of this instance whether any are tied to constant values.

  • has_tied_outputs

    Checks the output ports of this instance whether any are tied to constant values.

  • update_signedness

    Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

  • split

    Performs a bit-wise split on this instance.

  • p2v

    Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

  • ps2v

    Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

  • set

    Sets the signal on a port.

  • get_result

    Returns the result of this gate's operation for given Signals s1 and s2.

  • signals_in

    The input signals of the gate.

  • signal_out

    The output signal of the gate.

Attributes:

name instance-attribute

name: str

The name of the element.

!!! Do not modify this variable after instantiating it. Use NetlistElement.set_name() instead. Modifying this variable might lead to inconsistencies later on.

metadata class-attribute instance-attribute

Metadata of a netlist element.

Can be user-defined, or e. g. by Yosys (such as src for the HDL source). Is also grouped by categories, i.e. all metadata from Yosys can be accessed via Module.metadata["yosys"], or via Module.metadata.yosys, which both return a dictionary of all metadata. Read the documentation of MetaDataMixin for more information.

path property

Returns the InstancePath of the netlist element.

The InstancePath object is constructed using the element's type and its raw hierarchical path.

Returns:

  • InstancePath ( InstancePath ) –

    The hierarchical path of the netlist element.

type property

type: EType

The type of the element, which is an instance.

hierarchy_level property

hierarchy_level: int

The level of hierarchy of the element in the design.

The hierarchy level is the number of separators in the element's raw path. For example, a top-level instance has a hierarchy level of 0, while a direct submodule instance has a hierarchy level of 1.

Returns:

  • int ( int ) –

    The hierarchy level of the element.

has_parent property

has_parent: bool

Whether this object has a parent.

circuit property

circuit: 'Circuit'

The circuit object to which this netlist element belongs to.

  • For a module, returns the circuit to which the module belongs.
  • For any other netlist element, recursively returns the circuit of the parent, which ultimately leads to a module, to which the netlist element belongs.

Raises:

  • ParentNotFoundError

    If a parent cannot be resolved somewhere in the hierarchical chain.

  • ObjectNotFoundError

    If for a module no circuit is set.

has_circuit property

has_circuit: bool

Whether this netlist element has a defined circuit it belongs to.

Tries to access self.circuit and returns whether the call was successful. Can be used instead of a try-except clause around the call to NetlistElement.circuit.

locked property

locked: bool

True if this NetlistElement instance is locked (i.e. it is currently structurally unchangeable), False if it is mutable.

Can be changed via NetlistElement.change_mutability(bool).

Immutability is used to prevent accidental changes to the design.

is_placeholder_instance property

is_placeholder_instance: bool

A placeholder represents an element that does not have a specific path.

True if this NetlistElement instance represents a placeholder, False otherwise.

can_carry_signal property

can_carry_signal: bool

Whether this exact object is able to receive, pass or hold signal values.

True for ports (as they drive or receive values) and wires (as they pass the signals from driver to load ports) as well as their respective segments. False for instances and modules.

connections property

connections: Dict[str, Dict[int, WireSegmentPath]]

A dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port. Elements with no connection (i.e. the path is None) are excluded. In case these are needed, use Instance.get_connections() instead.

Example

{ 'port1': {1: WireSegmentPath('path/to/element1'), 2: WireSegmentPath('path/to/element2')}, 'port2': {1: WireSegmentPath('path/to/element3')} }

connection_str_paths property

connection_str_paths: Dict[str, Dict[int, str]]

Returns a dictionary mapping port names to their corresponding connection paths as strings.

The keys are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are the raw string paths.

Example

{ 'port1': {0: 'path.to.element1', 1: 'path.to.element2'}, 'port2': {0: 'path.to.element3'} }

ports property

A dictionary mapping port names to their corresponding Port objects.

The keys of the dictionary are the names of the ports. The values are Port objects representing the ports.

Returns:

input_ports property

input_ports: Tuple[Port[Instance], Port[Instance]]

The input ports of the gate as a 2-tuple.

output_ports property

output_ports: Tuple[Port[Instance], ...]

Returns a tuple of output ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as outputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the output ports.

has_unconnected_port_segments property

has_unconnected_port_segments: bool

Returns True if the instance has at least one unconnected port segment.

signals property

signals: Dict[str, SignalArray]

A dictionary with all signals currently present on all ports of this instance.

is_blackbox property

is_blackbox: bool

Flag indicating whether the instance represents neither a primitive element nor a module instance.

If True, this instance does not have a module definition, and is also not a basic component (i.e. a primitive gate instance) from the internal gate library, such as a gate or flip-flop.

y_width property

y_width: PositiveInt

Width of the gate, which is always 1 for gates that reduce N-bit inputs to 1 bit.

a_width property

a_width: PositiveInt

Width of the gate's A port.

b_width property

b_width: PositiveInt

Width of the gate's B port.

is_combinational property

is_combinational: bool

Whether instances of this gate are considered combinational gates.

True for combinational gates, such as AND gates or arithmetic gates. False for flip-flops and latches.

is_sequential property

is_sequential: bool

Whether instances of this gate are considered sequential gates.

False for combinational gates, such as AND gates or arithmetic gates. True for flip-flops and latches.

output_port property

output_port: Port[Instance]

The output port of the gate.

data_width property

data_width: int

The data width of this instance.

Defaults to the data width of the output port. Can be overwritten in extended classes.

In contrast to self.width, which is used for the creation and initialization, this property is linked to the data width of the output port. This property is useful when the data width of the output port can be changed.

a_signed property

a_signed: bool

The signedness of input port A.

b_signed property

b_signed: bool

The signedness of input port B.

truth_table property

truth_table: Dict[Tuple[Signal, Signal], Signal]

A simple truth table as a dictionary.

This dictionary contains the input-output mapping for unary gates that evaluate bitwise (e.g. AndGate, OrGate). Not implemented for arithmetic gates (e.g. Adder).

change_mutability

change_mutability(is_now_locked: bool, recursive: bool = False) -> Self

Change the mutability status of this instance and optionally its ports.

This method allows setting whether this instance can be modified or not. If recursive is set to True, it also applies the same mutability status to all ports of this instance.

Parameters:

  • is_now_locked

    (bool) –

    The new mutability status for this instance.

  • recursive

    (bool, default: False ) –

    Whether to apply the change recursively to its ports. Defaults to False.

evaluate

evaluate() -> None

Evaluates the gate's output signal based on its input signals.

This method is called when the gate's input signals change, and it updates the gate's output signal accordingly.

all_connections

all_connections(
    include_unconnected: bool,
) -> Dict[str, Dict[int, WireSegmentPath]]

Returns a dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port.

Parameters:

  • include_unconnected

    (bool) –

    Whether to include unconnected ports in the result.

Returns:

model_post_init

model_post_init(__context: object) -> None

Initializes the gate's ports and connections.

This method is called after the gate's attributes have been initialized, and it sets up the gate's ports and connections.

connect

connect(
    port_name: str,
    ws_path: Optional[WireSegmentPath],
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add connections to the specified port of this instance.

This method can establish multiple connections if a range of indices is provided.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection(s) should be established.

  • ws_path

    (Optional[WireSegmentPath]) –

    The path of the wire segment that will be connected to this port. If None, the associated port (segment) remains unconnected.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

Raises:

  • ObjectLockedError

    If this instance is currently locked, and no connection can be made.

disconnect

disconnect(port_name: str, index: Optional[int] = None) -> None

Remove an existing connection from a specified port of this instance.

This method disconnects the wire segment at the given index within the specified port_name.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be removed.

  • index

    (Optional[int], default: None ) –

    The bit index within the port for this disconnection. Defaults to None, which completely disconnects the port.

Raises:

get_connection

get_connection(
    port_name: str, index: Optional[NonNegativeInt] = None
) -> Union[WireSegmentPath, Dict[int, WireSegmentPath], None]

Retrieve the connection path associated with a specified port and bit index.

If index is provided, this method returns the wire segment path connected to that specific bit within the port. Otherwise, it returns all connections for the given port as a dictionary mapping indices to WireSegmentPaths.

Parameters:

  • port_name

    (str) –

    The name of the port for which to retrieve the connection(s).

  • index

    (Optional[NonNegativeInt], default: None ) –

    The bit index within the port. Defaults to None.

Returns:

modify_connection

modify_connection(
    port_name: str, ws_path: WireSegmentPath, index: NonNegativeInt = 0
) -> None

Modify an existing connection within a specified port of this instance.

This method updates the wire segment path at the given index within the specified port_name. If the index does not exist yet, it is newly added, changing the width of the port.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be modified.

  • ws_path

    (WireSegmentPath) –

    The new wire segment path for this connection.

  • index

    (NonNegativeInt, default: 0 ) –

    The bit index within the port. Defaults to 0.

connect_modify

connect_modify(
    port_name: str,
    ws_path: WireSegmentPath,
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add a new connection or modify an existing one within the specified port of this instance.

If the connection already exists at the given index and port_name, it will be modified. Otherwise, a new connection is added.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be established or updated.

  • ws_path

    (WireSegmentPath) –

    The path of the wire segment that will be connected to this port.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

tie_port

tie_port(name: str, index: NonNegativeInt, sig_value: LogicLevel) -> None

Set a constant signal value for the specified port and bit index.

If the specified port does not exist, an error message is logged and the function returns False. Otherwise, the method tries to set the constant signal value for that port and returns True if successful.

Does not work for instance output ports, as they are always driven by their parent instances.

Parameters:

  • name

    (str) –

    The name of the port.

  • index

    (NonNegativeInt) –

    The bit index within the port.

  • sig_value

    (LogicLevel) –

    The constant signal value to be set ('0', '1', or 'Z').

Raises:

  • ObjectNotFoundError

    If no such port or port segment exists.

  • AlreadyConnectedError

    (raised by: PortSegment.tie_signal) If this segment is belongs to a load port and is already connected to a wire, from which it receives its value.

  • InvalidDirectionError

    (raised by: PortSegment.tie_signal) If this port segment belongs to an instance output port, which is driven by the instance inputs and the instance's internal logic.

  • InvalidSignalError

    (raised by: PortSegment.tie_signal) If an invalid value is provided.

has_tied_ports

has_tied_ports() -> bool

Checks the ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any ports of this instance are tied to constant values. False otherwise, i.e. all ports are connected to wires.

has_tied_inputs

has_tied_inputs() -> bool

Checks the input ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any input ports of this instance are tied to constant values. False otherwise, i.e. all input ports are connected to wires.

has_tied_outputs

has_tied_outputs() -> bool

Checks the output ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any output ports of this instance are tied to constant values. False otherwise, i.e. all output ports are connected to wires.

update_signedness

update_signedness(port_name: str) -> None

Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

Parameters:

  • port_name

    (str) –

    The name of the port, of which the signedness value is retrieved.

split

split() -> Dict[NonNegativeInt, Self]

Performs a bit-wise split on this instance.

If this instance supports splitting and has a data width of n bit, this method splits this instance into n 1-bit instances. This works for instances, where each output bit depends only on the corresponding input bit(s), e.g. an AND gate or a D-Flipflop.

Returns:

  • Dict[NonNegativeInt, Self]

    Dict[int, Instance]: An n-bit large dictionary, where each key conforms to a bit of the original instance, and each value is an 1-bit instance representing the corresponding "slice" of the original instance.

Raises:

  • SplittingUnsupportedError

    If this instance does not support splitting. Happens for any gate or instance whose behavior depends on the whole bus, and splitting would make it lose its meaning.

p2v

p2v(
    port: ANY_PORT,
    exclude_indices: Optional[List[int]] = None,
    include_indices: Optional[List[int]] = None,
) -> str

Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a Port object and converts them to their corresponding Verilog signal structure (p2v -> Port to Verilog signal syntax). For each segment of the port, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port is set to a constant, the corresponding constant wire segment placeholder is used instead. Port segments can be excluded from the conversion by providing a list of indices to the exclude_indices parameter, indicating which segments should be excluded from the conversion (e.g. segments that are known to be unconnected). Vice versa, only a certain subset of the port's segments may be converted to Verilog syntax, if include_indices is a given list of port indices. All indices not present in the list will be excluded from the conversion.

Parameters:

  • port

    (Port) –

    The Port object to convert.

  • exclude_indices

    (List[int], default: None ) –

    A list of indices to exclude from the conversion. Defaults to None.

  • include_indices

    (List[int], default: None ) –

    A list of indices (i.e. port slices) to include only for the conversion. Defaults to None.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

  • ObjectNotFoundError

    If the wire connected to a certain port segment could not be found.

  • UnsupportedOperationError

    If both exclude_indices and include_indices are specified. Only one of both may be given when calling this method.

ps2v

Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a PortSegment dictionary and converts them to their corresponding Verilog signal structure (ps2v -> PortSegment to Verilog signal syntax). For each segment, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port segment is set to a constant, the corresponding constant wire segment placeholder is used instead.

Parameters:

  • ps_dict

    (Dict[int, PortSegment]) –

    The PortSegment dictionary to convert. Each key (int) conforms to the index of the associated PortSegment object.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

set

set(
    port_name: str,
    new_signal: SignalOrLogicLevel,
    idx: Union[int, List[int]] = 0,
) -> None

Sets the signal on a port.

Parameters:

  • port_name

    (str) –

    The name of the port to set the signal on.

  • new_signal

    (Signal) –

    The new signal value.

  • idx

    (Union[int, List[int]], default: 0 ) –

    The index (or indices) to apply the given signal to. Can either be an integer (single index to set) or an iterable of integers (e.g. a list of indices). For every integer of the iterable the signal value of the corresponding port index is set to the given new_signal. Defaults to 0.

Example

from netlist_carpentry.utils.gate_factory import and_gate module = Module(name='m') a = module.create_port('a', 'input', width=6) instance = and_gate(module, 'inst', A=a)

This sets the value of bit 0 of port A to HIGH

instance.set('A', 1, 0) instance.ports['A'].signal_str 'xxxxx1'

This sets the value of bits 1, 3 and 5 of port A to LOW, leaving the other bits as they already are.

instance.set('A', 0, [1, 3, 5]) instance.ports['A'].signal_str '0x0x01'

get_result

get_result(s1: Signal, s2: Signal) -> Signal

Returns the result of this gate's operation for given Signals s1 and s2.

This method is only implemented for bitwise evaluating gates (e.g. AndGate, OrGate). This method raises an UnsupportedOperationError if used on other gates (e.g. Adder).

For vector-level operations on full signal arrays, use :meth:get_result_vector instead.

Parameters:

  • s1

    (Signal) –

    The first Signal, i.e. the first operand.

  • s2

    (Signal) –

    The second Signal, i.e. the second operand.

Raises:

Returns:

  • Signal ( Signal ) –

    The result of this gate's operation on the given signals.

signals_in

signals_in(idx: NonNegativeInt = 0) -> Tuple[Signal, Signal]

The input signals of the gate.

Returns:

signal_out

signal_out(idx: NonNegativeInt = 0) -> Signal

The output signal of the gate.

Returns:

  • Signal ( Signal ) –

    The output signal of the gate.

CaseNotEqual

Bases: BinaryNto1Gate, BaseModel

A CASE-NOT-EQUAL gate.

A CASE-NOT-EQUAL gate is a gate that produces a HIGH output signal only if both input signals have different values. Otherwise (if both are equal), it produces a LOW output signal.

Unlike the normal inequality comparison (NotEqual gate, §ne) that can give x as output, this gate produces an exact inequality comparison. It will strictly give 0 or 1 as output, even if input includes x or z values, implementing the Verilog !== operator.

Methods:

  • change_mutability

    Change the mutability status of this instance and optionally its ports.

  • evaluate

    Evaluates the gate's output signal based on its input signals.

  • all_connections

    Returns a dictionary mapping port names to their corresponding connection paths.

  • model_post_init

    Initializes the gate's ports and connections.

  • connect

    Add connections to the specified port of this instance.

  • disconnect

    Remove an existing connection from a specified port of this instance.

  • get_connection

    Retrieve the connection path associated with a specified port and bit index.

  • modify_connection

    Modify an existing connection within a specified port of this instance.

  • connect_modify

    Add a new connection or modify an existing one within the specified port of this instance.

  • tie_port

    Set a constant signal value for the specified port and bit index.

  • has_tied_ports

    Checks the ports of this instance whether any are tied to constant values.

  • has_tied_inputs

    Checks the input ports of this instance whether any are tied to constant values.

  • has_tied_outputs

    Checks the output ports of this instance whether any are tied to constant values.

  • update_signedness

    Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

  • split

    Performs a bit-wise split on this instance.

  • p2v

    Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

  • ps2v

    Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

  • set

    Sets the signal on a port.

  • get_result

    Returns the result of this gate's operation for given Signals s1 and s2.

  • signals_in

    The input signals of the gate.

  • signal_out

    The output signal of the gate.

Attributes:

name instance-attribute

name: str

The name of the element.

!!! Do not modify this variable after instantiating it. Use NetlistElement.set_name() instead. Modifying this variable might lead to inconsistencies later on.

metadata class-attribute instance-attribute

Metadata of a netlist element.

Can be user-defined, or e. g. by Yosys (such as src for the HDL source). Is also grouped by categories, i.e. all metadata from Yosys can be accessed via Module.metadata["yosys"], or via Module.metadata.yosys, which both return a dictionary of all metadata. Read the documentation of MetaDataMixin for more information.

path property

Returns the InstancePath of the netlist element.

The InstancePath object is constructed using the element's type and its raw hierarchical path.

Returns:

  • InstancePath ( InstancePath ) –

    The hierarchical path of the netlist element.

type property

type: EType

The type of the element, which is an instance.

hierarchy_level property

hierarchy_level: int

The level of hierarchy of the element in the design.

The hierarchy level is the number of separators in the element's raw path. For example, a top-level instance has a hierarchy level of 0, while a direct submodule instance has a hierarchy level of 1.

Returns:

  • int ( int ) –

    The hierarchy level of the element.

has_parent property

has_parent: bool

Whether this object has a parent.

circuit property

circuit: 'Circuit'

The circuit object to which this netlist element belongs to.

  • For a module, returns the circuit to which the module belongs.
  • For any other netlist element, recursively returns the circuit of the parent, which ultimately leads to a module, to which the netlist element belongs.

Raises:

  • ParentNotFoundError

    If a parent cannot be resolved somewhere in the hierarchical chain.

  • ObjectNotFoundError

    If for a module no circuit is set.

has_circuit property

has_circuit: bool

Whether this netlist element has a defined circuit it belongs to.

Tries to access self.circuit and returns whether the call was successful. Can be used instead of a try-except clause around the call to NetlistElement.circuit.

locked property

locked: bool

True if this NetlistElement instance is locked (i.e. it is currently structurally unchangeable), False if it is mutable.

Can be changed via NetlistElement.change_mutability(bool).

Immutability is used to prevent accidental changes to the design.

is_placeholder_instance property

is_placeholder_instance: bool

A placeholder represents an element that does not have a specific path.

True if this NetlistElement instance represents a placeholder, False otherwise.

can_carry_signal property

can_carry_signal: bool

Whether this exact object is able to receive, pass or hold signal values.

True for ports (as they drive or receive values) and wires (as they pass the signals from driver to load ports) as well as their respective segments. False for instances and modules.

connections property

connections: Dict[str, Dict[int, WireSegmentPath]]

A dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port. Elements with no connection (i.e. the path is None) are excluded. In case these are needed, use Instance.get_connections() instead.

Example

{ 'port1': {1: WireSegmentPath('path/to/element1'), 2: WireSegmentPath('path/to/element2')}, 'port2': {1: WireSegmentPath('path/to/element3')} }

connection_str_paths property

connection_str_paths: Dict[str, Dict[int, str]]

Returns a dictionary mapping port names to their corresponding connection paths as strings.

The keys are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are the raw string paths.

Example

{ 'port1': {0: 'path.to.element1', 1: 'path.to.element2'}, 'port2': {0: 'path.to.element3'} }

ports property

A dictionary mapping port names to their corresponding Port objects.

The keys of the dictionary are the names of the ports. The values are Port objects representing the ports.

Returns:

input_ports property

input_ports: Tuple[Port[Instance], Port[Instance]]

The input ports of the gate as a 2-tuple.

output_ports property

output_ports: Tuple[Port[Instance], ...]

Returns a tuple of output ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as outputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the output ports.

has_unconnected_port_segments property

has_unconnected_port_segments: bool

Returns True if the instance has at least one unconnected port segment.

signals property

signals: Dict[str, SignalArray]

A dictionary with all signals currently present on all ports of this instance.

is_blackbox property

is_blackbox: bool

Flag indicating whether the instance represents neither a primitive element nor a module instance.

If True, this instance does not have a module definition, and is also not a basic component (i.e. a primitive gate instance) from the internal gate library, such as a gate or flip-flop.

y_width property

y_width: PositiveInt

Width of the gate, which is always 1 for gates that reduce N-bit inputs to 1 bit.

a_width property

a_width: PositiveInt

Width of the gate's A port.

b_width property

b_width: PositiveInt

Width of the gate's B port.

is_combinational property

is_combinational: bool

Whether instances of this gate are considered combinational gates.

True for combinational gates, such as AND gates or arithmetic gates. False for flip-flops and latches.

is_sequential property

is_sequential: bool

Whether instances of this gate are considered sequential gates.

False for combinational gates, such as AND gates or arithmetic gates. True for flip-flops and latches.

output_port property

output_port: Port[Instance]

The output port of the gate.

data_width property

data_width: int

The data width of this instance.

Defaults to the data width of the output port. Can be overwritten in extended classes.

In contrast to self.width, which is used for the creation and initialization, this property is linked to the data width of the output port. This property is useful when the data width of the output port can be changed.

a_signed property

a_signed: bool

The signedness of input port A.

b_signed property

b_signed: bool

The signedness of input port B.

truth_table property

truth_table: Dict[Tuple[Signal, Signal], Signal]

A simple truth table as a dictionary.

This dictionary contains the input-output mapping for unary gates that evaluate bitwise (e.g. AndGate, OrGate). Not implemented for arithmetic gates (e.g. Adder).

change_mutability

change_mutability(is_now_locked: bool, recursive: bool = False) -> Self

Change the mutability status of this instance and optionally its ports.

This method allows setting whether this instance can be modified or not. If recursive is set to True, it also applies the same mutability status to all ports of this instance.

Parameters:

  • is_now_locked

    (bool) –

    The new mutability status for this instance.

  • recursive

    (bool, default: False ) –

    Whether to apply the change recursively to its ports. Defaults to False.

evaluate

evaluate() -> None

Evaluates the gate's output signal based on its input signals.

This method is called when the gate's input signals change, and it updates the gate's output signal accordingly.

all_connections

all_connections(
    include_unconnected: bool,
) -> Dict[str, Dict[int, WireSegmentPath]]

Returns a dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port.

Parameters:

  • include_unconnected

    (bool) –

    Whether to include unconnected ports in the result.

Returns:

model_post_init

model_post_init(__context: object) -> None

Initializes the gate's ports and connections.

This method is called after the gate's attributes have been initialized, and it sets up the gate's ports and connections.

connect

connect(
    port_name: str,
    ws_path: Optional[WireSegmentPath],
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add connections to the specified port of this instance.

This method can establish multiple connections if a range of indices is provided.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection(s) should be established.

  • ws_path

    (Optional[WireSegmentPath]) –

    The path of the wire segment that will be connected to this port. If None, the associated port (segment) remains unconnected.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

Raises:

  • ObjectLockedError

    If this instance is currently locked, and no connection can be made.

disconnect

disconnect(port_name: str, index: Optional[int] = None) -> None

Remove an existing connection from a specified port of this instance.

This method disconnects the wire segment at the given index within the specified port_name.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be removed.

  • index

    (Optional[int], default: None ) –

    The bit index within the port for this disconnection. Defaults to None, which completely disconnects the port.

Raises:

get_connection

get_connection(
    port_name: str, index: Optional[NonNegativeInt] = None
) -> Union[WireSegmentPath, Dict[int, WireSegmentPath], None]

Retrieve the connection path associated with a specified port and bit index.

If index is provided, this method returns the wire segment path connected to that specific bit within the port. Otherwise, it returns all connections for the given port as a dictionary mapping indices to WireSegmentPaths.

Parameters:

  • port_name

    (str) –

    The name of the port for which to retrieve the connection(s).

  • index

    (Optional[NonNegativeInt], default: None ) –

    The bit index within the port. Defaults to None.

Returns:

modify_connection

modify_connection(
    port_name: str, ws_path: WireSegmentPath, index: NonNegativeInt = 0
) -> None

Modify an existing connection within a specified port of this instance.

This method updates the wire segment path at the given index within the specified port_name. If the index does not exist yet, it is newly added, changing the width of the port.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be modified.

  • ws_path

    (WireSegmentPath) –

    The new wire segment path for this connection.

  • index

    (NonNegativeInt, default: 0 ) –

    The bit index within the port. Defaults to 0.

connect_modify

connect_modify(
    port_name: str,
    ws_path: WireSegmentPath,
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add a new connection or modify an existing one within the specified port of this instance.

If the connection already exists at the given index and port_name, it will be modified. Otherwise, a new connection is added.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be established or updated.

  • ws_path

    (WireSegmentPath) –

    The path of the wire segment that will be connected to this port.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

tie_port

tie_port(name: str, index: NonNegativeInt, sig_value: LogicLevel) -> None

Set a constant signal value for the specified port and bit index.

If the specified port does not exist, an error message is logged and the function returns False. Otherwise, the method tries to set the constant signal value for that port and returns True if successful.

Does not work for instance output ports, as they are always driven by their parent instances.

Parameters:

  • name

    (str) –

    The name of the port.

  • index

    (NonNegativeInt) –

    The bit index within the port.

  • sig_value

    (LogicLevel) –

    The constant signal value to be set ('0', '1', or 'Z').

Raises:

  • ObjectNotFoundError

    If no such port or port segment exists.

  • AlreadyConnectedError

    (raised by: PortSegment.tie_signal) If this segment is belongs to a load port and is already connected to a wire, from which it receives its value.

  • InvalidDirectionError

    (raised by: PortSegment.tie_signal) If this port segment belongs to an instance output port, which is driven by the instance inputs and the instance's internal logic.

  • InvalidSignalError

    (raised by: PortSegment.tie_signal) If an invalid value is provided.

has_tied_ports

has_tied_ports() -> bool

Checks the ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any ports of this instance are tied to constant values. False otherwise, i.e. all ports are connected to wires.

has_tied_inputs

has_tied_inputs() -> bool

Checks the input ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any input ports of this instance are tied to constant values. False otherwise, i.e. all input ports are connected to wires.

has_tied_outputs

has_tied_outputs() -> bool

Checks the output ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any output ports of this instance are tied to constant values. False otherwise, i.e. all output ports are connected to wires.

update_signedness

update_signedness(port_name: str) -> None

Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

Parameters:

  • port_name

    (str) –

    The name of the port, of which the signedness value is retrieved.

split

split() -> Dict[NonNegativeInt, Self]

Performs a bit-wise split on this instance.

If this instance supports splitting and has a data width of n bit, this method splits this instance into n 1-bit instances. This works for instances, where each output bit depends only on the corresponding input bit(s), e.g. an AND gate or a D-Flipflop.

Returns:

  • Dict[NonNegativeInt, Self]

    Dict[int, Instance]: An n-bit large dictionary, where each key conforms to a bit of the original instance, and each value is an 1-bit instance representing the corresponding "slice" of the original instance.

Raises:

  • SplittingUnsupportedError

    If this instance does not support splitting. Happens for any gate or instance whose behavior depends on the whole bus, and splitting would make it lose its meaning.

p2v

p2v(
    port: ANY_PORT,
    exclude_indices: Optional[List[int]] = None,
    include_indices: Optional[List[int]] = None,
) -> str

Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a Port object and converts them to their corresponding Verilog signal structure (p2v -> Port to Verilog signal syntax). For each segment of the port, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port is set to a constant, the corresponding constant wire segment placeholder is used instead. Port segments can be excluded from the conversion by providing a list of indices to the exclude_indices parameter, indicating which segments should be excluded from the conversion (e.g. segments that are known to be unconnected). Vice versa, only a certain subset of the port's segments may be converted to Verilog syntax, if include_indices is a given list of port indices. All indices not present in the list will be excluded from the conversion.

Parameters:

  • port

    (Port) –

    The Port object to convert.

  • exclude_indices

    (List[int], default: None ) –

    A list of indices to exclude from the conversion. Defaults to None.

  • include_indices

    (List[int], default: None ) –

    A list of indices (i.e. port slices) to include only for the conversion. Defaults to None.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

  • ObjectNotFoundError

    If the wire connected to a certain port segment could not be found.

  • UnsupportedOperationError

    If both exclude_indices and include_indices are specified. Only one of both may be given when calling this method.

ps2v

Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a PortSegment dictionary and converts them to their corresponding Verilog signal structure (ps2v -> PortSegment to Verilog signal syntax). For each segment, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port segment is set to a constant, the corresponding constant wire segment placeholder is used instead.

Parameters:

  • ps_dict

    (Dict[int, PortSegment]) –

    The PortSegment dictionary to convert. Each key (int) conforms to the index of the associated PortSegment object.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

set

set(
    port_name: str,
    new_signal: SignalOrLogicLevel,
    idx: Union[int, List[int]] = 0,
) -> None

Sets the signal on a port.

Parameters:

  • port_name

    (str) –

    The name of the port to set the signal on.

  • new_signal

    (Signal) –

    The new signal value.

  • idx

    (Union[int, List[int]], default: 0 ) –

    The index (or indices) to apply the given signal to. Can either be an integer (single index to set) or an iterable of integers (e.g. a list of indices). For every integer of the iterable the signal value of the corresponding port index is set to the given new_signal. Defaults to 0.

Example

from netlist_carpentry.utils.gate_factory import and_gate module = Module(name='m') a = module.create_port('a', 'input', width=6) instance = and_gate(module, 'inst', A=a)

This sets the value of bit 0 of port A to HIGH

instance.set('A', 1, 0) instance.ports['A'].signal_str 'xxxxx1'

This sets the value of bits 1, 3 and 5 of port A to LOW, leaving the other bits as they already are.

instance.set('A', 0, [1, 3, 5]) instance.ports['A'].signal_str '0x0x01'

get_result

get_result(s1: Signal, s2: Signal) -> Signal

Returns the result of this gate's operation for given Signals s1 and s2.

This method is only implemented for bitwise evaluating gates (e.g. AndGate, OrGate). This method raises an UnsupportedOperationError if used on other gates (e.g. Adder).

For vector-level operations on full signal arrays, use :meth:get_result_vector instead.

Parameters:

  • s1

    (Signal) –

    The first Signal, i.e. the first operand.

  • s2

    (Signal) –

    The second Signal, i.e. the second operand.

Raises:

Returns:

  • Signal ( Signal ) –

    The result of this gate's operation on the given signals.

signals_in

signals_in(idx: NonNegativeInt = 0) -> Tuple[Signal, Signal]

The input signals of the gate.

Returns:

signal_out

signal_out(idx: NonNegativeInt = 0) -> Signal

The output signal of the gate.

Returns:

  • Signal ( Signal ) –

    The output signal of the gate.

GreaterThan

Bases: BinaryNto1Gate, BaseModel

A GREATER-THAN gate.

A GREATER-THAN gate is a gate that produces a HIGH output signal only if its "left" input signal value is greater than its "right" input signal. Otherwise, it produces a LOW output signal.

Methods:

  • change_mutability

    Change the mutability status of this instance and optionally its ports.

  • evaluate

    Evaluates the gate's output signal based on its input signals.

  • all_connections

    Returns a dictionary mapping port names to their corresponding connection paths.

  • model_post_init

    Initializes the gate's ports and connections.

  • connect

    Add connections to the specified port of this instance.

  • disconnect

    Remove an existing connection from a specified port of this instance.

  • get_connection

    Retrieve the connection path associated with a specified port and bit index.

  • modify_connection

    Modify an existing connection within a specified port of this instance.

  • connect_modify

    Add a new connection or modify an existing one within the specified port of this instance.

  • tie_port

    Set a constant signal value for the specified port and bit index.

  • has_tied_ports

    Checks the ports of this instance whether any are tied to constant values.

  • has_tied_inputs

    Checks the input ports of this instance whether any are tied to constant values.

  • has_tied_outputs

    Checks the output ports of this instance whether any are tied to constant values.

  • update_signedness

    Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

  • split

    Performs a bit-wise split on this instance.

  • p2v

    Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

  • ps2v

    Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

  • set

    Sets the signal on a port.

  • get_result

    Returns the result of this gate's operation for given Signals s1 and s2.

  • signals_in

    The input signals of the gate.

  • signal_out

    The output signal of the gate.

Attributes:

name instance-attribute

name: str

The name of the element.

!!! Do not modify this variable after instantiating it. Use NetlistElement.set_name() instead. Modifying this variable might lead to inconsistencies later on.

metadata class-attribute instance-attribute

Metadata of a netlist element.

Can be user-defined, or e. g. by Yosys (such as src for the HDL source). Is also grouped by categories, i.e. all metadata from Yosys can be accessed via Module.metadata["yosys"], or via Module.metadata.yosys, which both return a dictionary of all metadata. Read the documentation of MetaDataMixin for more information.

path property

Returns the InstancePath of the netlist element.

The InstancePath object is constructed using the element's type and its raw hierarchical path.

Returns:

  • InstancePath ( InstancePath ) –

    The hierarchical path of the netlist element.

type property

type: EType

The type of the element, which is an instance.

hierarchy_level property

hierarchy_level: int

The level of hierarchy of the element in the design.

The hierarchy level is the number of separators in the element's raw path. For example, a top-level instance has a hierarchy level of 0, while a direct submodule instance has a hierarchy level of 1.

Returns:

  • int ( int ) –

    The hierarchy level of the element.

has_parent property

has_parent: bool

Whether this object has a parent.

circuit property

circuit: 'Circuit'

The circuit object to which this netlist element belongs to.

  • For a module, returns the circuit to which the module belongs.
  • For any other netlist element, recursively returns the circuit of the parent, which ultimately leads to a module, to which the netlist element belongs.

Raises:

  • ParentNotFoundError

    If a parent cannot be resolved somewhere in the hierarchical chain.

  • ObjectNotFoundError

    If for a module no circuit is set.

has_circuit property

has_circuit: bool

Whether this netlist element has a defined circuit it belongs to.

Tries to access self.circuit and returns whether the call was successful. Can be used instead of a try-except clause around the call to NetlistElement.circuit.

locked property

locked: bool

True if this NetlistElement instance is locked (i.e. it is currently structurally unchangeable), False if it is mutable.

Can be changed via NetlistElement.change_mutability(bool).

Immutability is used to prevent accidental changes to the design.

is_placeholder_instance property

is_placeholder_instance: bool

A placeholder represents an element that does not have a specific path.

True if this NetlistElement instance represents a placeholder, False otherwise.

can_carry_signal property

can_carry_signal: bool

Whether this exact object is able to receive, pass or hold signal values.

True for ports (as they drive or receive values) and wires (as they pass the signals from driver to load ports) as well as their respective segments. False for instances and modules.

connections property

connections: Dict[str, Dict[int, WireSegmentPath]]

A dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port. Elements with no connection (i.e. the path is None) are excluded. In case these are needed, use Instance.get_connections() instead.

Example

{ 'port1': {1: WireSegmentPath('path/to/element1'), 2: WireSegmentPath('path/to/element2')}, 'port2': {1: WireSegmentPath('path/to/element3')} }

connection_str_paths property

connection_str_paths: Dict[str, Dict[int, str]]

Returns a dictionary mapping port names to their corresponding connection paths as strings.

The keys are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are the raw string paths.

Example

{ 'port1': {0: 'path.to.element1', 1: 'path.to.element2'}, 'port2': {0: 'path.to.element3'} }

ports property

A dictionary mapping port names to their corresponding Port objects.

The keys of the dictionary are the names of the ports. The values are Port objects representing the ports.

Returns:

input_ports property

input_ports: Tuple[Port[Instance], Port[Instance]]

The input ports of the gate as a 2-tuple.

output_ports property

output_ports: Tuple[Port[Instance], ...]

Returns a tuple of output ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as outputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the output ports.

has_unconnected_port_segments property

has_unconnected_port_segments: bool

Returns True if the instance has at least one unconnected port segment.

signals property

signals: Dict[str, SignalArray]

A dictionary with all signals currently present on all ports of this instance.

is_blackbox property

is_blackbox: bool

Flag indicating whether the instance represents neither a primitive element nor a module instance.

If True, this instance does not have a module definition, and is also not a basic component (i.e. a primitive gate instance) from the internal gate library, such as a gate or flip-flop.

y_width property

y_width: PositiveInt

Width of the gate, which is always 1 for gates that reduce N-bit inputs to 1 bit.

a_width property

a_width: PositiveInt

Width of the gate's A port.

b_width property

b_width: PositiveInt

Width of the gate's B port.

is_combinational property

is_combinational: bool

Whether instances of this gate are considered combinational gates.

True for combinational gates, such as AND gates or arithmetic gates. False for flip-flops and latches.

is_sequential property

is_sequential: bool

Whether instances of this gate are considered sequential gates.

False for combinational gates, such as AND gates or arithmetic gates. True for flip-flops and latches.

output_port property

output_port: Port[Instance]

The output port of the gate.

data_width property

data_width: int

The data width of this instance.

Defaults to the data width of the output port. Can be overwritten in extended classes.

In contrast to self.width, which is used for the creation and initialization, this property is linked to the data width of the output port. This property is useful when the data width of the output port can be changed.

a_signed property

a_signed: bool

The signedness of input port A.

b_signed property

b_signed: bool

The signedness of input port B.

truth_table property

truth_table: Dict[Tuple[Signal, Signal], Signal]

A simple truth table as a dictionary.

This dictionary contains the input-output mapping for unary gates that evaluate bitwise (e.g. AndGate, OrGate). Not implemented for arithmetic gates (e.g. Adder).

change_mutability

change_mutability(is_now_locked: bool, recursive: bool = False) -> Self

Change the mutability status of this instance and optionally its ports.

This method allows setting whether this instance can be modified or not. If recursive is set to True, it also applies the same mutability status to all ports of this instance.

Parameters:

  • is_now_locked

    (bool) –

    The new mutability status for this instance.

  • recursive

    (bool, default: False ) –

    Whether to apply the change recursively to its ports. Defaults to False.

evaluate

evaluate() -> None

Evaluates the gate's output signal based on its input signals.

This method is called when the gate's input signals change, and it updates the gate's output signal accordingly.

all_connections

all_connections(
    include_unconnected: bool,
) -> Dict[str, Dict[int, WireSegmentPath]]

Returns a dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port.

Parameters:

  • include_unconnected

    (bool) –

    Whether to include unconnected ports in the result.

Returns:

model_post_init

model_post_init(__context: object) -> None

Initializes the gate's ports and connections.

This method is called after the gate's attributes have been initialized, and it sets up the gate's ports and connections.

connect

connect(
    port_name: str,
    ws_path: Optional[WireSegmentPath],
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add connections to the specified port of this instance.

This method can establish multiple connections if a range of indices is provided.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection(s) should be established.

  • ws_path

    (Optional[WireSegmentPath]) –

    The path of the wire segment that will be connected to this port. If None, the associated port (segment) remains unconnected.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

Raises:

  • ObjectLockedError

    If this instance is currently locked, and no connection can be made.

disconnect

disconnect(port_name: str, index: Optional[int] = None) -> None

Remove an existing connection from a specified port of this instance.

This method disconnects the wire segment at the given index within the specified port_name.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be removed.

  • index

    (Optional[int], default: None ) –

    The bit index within the port for this disconnection. Defaults to None, which completely disconnects the port.

Raises:

get_connection

get_connection(
    port_name: str, index: Optional[NonNegativeInt] = None
) -> Union[WireSegmentPath, Dict[int, WireSegmentPath], None]

Retrieve the connection path associated with a specified port and bit index.

If index is provided, this method returns the wire segment path connected to that specific bit within the port. Otherwise, it returns all connections for the given port as a dictionary mapping indices to WireSegmentPaths.

Parameters:

  • port_name

    (str) –

    The name of the port for which to retrieve the connection(s).

  • index

    (Optional[NonNegativeInt], default: None ) –

    The bit index within the port. Defaults to None.

Returns:

modify_connection

modify_connection(
    port_name: str, ws_path: WireSegmentPath, index: NonNegativeInt = 0
) -> None

Modify an existing connection within a specified port of this instance.

This method updates the wire segment path at the given index within the specified port_name. If the index does not exist yet, it is newly added, changing the width of the port.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be modified.

  • ws_path

    (WireSegmentPath) –

    The new wire segment path for this connection.

  • index

    (NonNegativeInt, default: 0 ) –

    The bit index within the port. Defaults to 0.

connect_modify

connect_modify(
    port_name: str,
    ws_path: WireSegmentPath,
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add a new connection or modify an existing one within the specified port of this instance.

If the connection already exists at the given index and port_name, it will be modified. Otherwise, a new connection is added.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be established or updated.

  • ws_path

    (WireSegmentPath) –

    The path of the wire segment that will be connected to this port.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

tie_port

tie_port(name: str, index: NonNegativeInt, sig_value: LogicLevel) -> None

Set a constant signal value for the specified port and bit index.

If the specified port does not exist, an error message is logged and the function returns False. Otherwise, the method tries to set the constant signal value for that port and returns True if successful.

Does not work for instance output ports, as they are always driven by their parent instances.

Parameters:

  • name

    (str) –

    The name of the port.

  • index

    (NonNegativeInt) –

    The bit index within the port.

  • sig_value

    (LogicLevel) –

    The constant signal value to be set ('0', '1', or 'Z').

Raises:

  • ObjectNotFoundError

    If no such port or port segment exists.

  • AlreadyConnectedError

    (raised by: PortSegment.tie_signal) If this segment is belongs to a load port and is already connected to a wire, from which it receives its value.

  • InvalidDirectionError

    (raised by: PortSegment.tie_signal) If this port segment belongs to an instance output port, which is driven by the instance inputs and the instance's internal logic.

  • InvalidSignalError

    (raised by: PortSegment.tie_signal) If an invalid value is provided.

has_tied_ports

has_tied_ports() -> bool

Checks the ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any ports of this instance are tied to constant values. False otherwise, i.e. all ports are connected to wires.

has_tied_inputs

has_tied_inputs() -> bool

Checks the input ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any input ports of this instance are tied to constant values. False otherwise, i.e. all input ports are connected to wires.

has_tied_outputs

has_tied_outputs() -> bool

Checks the output ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any output ports of this instance are tied to constant values. False otherwise, i.e. all output ports are connected to wires.

update_signedness

update_signedness(port_name: str) -> None

Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

Parameters:

  • port_name

    (str) –

    The name of the port, of which the signedness value is retrieved.

split

split() -> Dict[NonNegativeInt, Self]

Performs a bit-wise split on this instance.

If this instance supports splitting and has a data width of n bit, this method splits this instance into n 1-bit instances. This works for instances, where each output bit depends only on the corresponding input bit(s), e.g. an AND gate or a D-Flipflop.

Returns:

  • Dict[NonNegativeInt, Self]

    Dict[int, Instance]: An n-bit large dictionary, where each key conforms to a bit of the original instance, and each value is an 1-bit instance representing the corresponding "slice" of the original instance.

Raises:

  • SplittingUnsupportedError

    If this instance does not support splitting. Happens for any gate or instance whose behavior depends on the whole bus, and splitting would make it lose its meaning.

p2v

p2v(
    port: ANY_PORT,
    exclude_indices: Optional[List[int]] = None,
    include_indices: Optional[List[int]] = None,
) -> str

Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a Port object and converts them to their corresponding Verilog signal structure (p2v -> Port to Verilog signal syntax). For each segment of the port, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port is set to a constant, the corresponding constant wire segment placeholder is used instead. Port segments can be excluded from the conversion by providing a list of indices to the exclude_indices parameter, indicating which segments should be excluded from the conversion (e.g. segments that are known to be unconnected). Vice versa, only a certain subset of the port's segments may be converted to Verilog syntax, if include_indices is a given list of port indices. All indices not present in the list will be excluded from the conversion.

Parameters:

  • port

    (Port) –

    The Port object to convert.

  • exclude_indices

    (List[int], default: None ) –

    A list of indices to exclude from the conversion. Defaults to None.

  • include_indices

    (List[int], default: None ) –

    A list of indices (i.e. port slices) to include only for the conversion. Defaults to None.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

  • ObjectNotFoundError

    If the wire connected to a certain port segment could not be found.

  • UnsupportedOperationError

    If both exclude_indices and include_indices are specified. Only one of both may be given when calling this method.

ps2v

Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a PortSegment dictionary and converts them to their corresponding Verilog signal structure (ps2v -> PortSegment to Verilog signal syntax). For each segment, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port segment is set to a constant, the corresponding constant wire segment placeholder is used instead.

Parameters:

  • ps_dict

    (Dict[int, PortSegment]) –

    The PortSegment dictionary to convert. Each key (int) conforms to the index of the associated PortSegment object.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

set

set(
    port_name: str,
    new_signal: SignalOrLogicLevel,
    idx: Union[int, List[int]] = 0,
) -> None

Sets the signal on a port.

Parameters:

  • port_name

    (str) –

    The name of the port to set the signal on.

  • new_signal

    (Signal) –

    The new signal value.

  • idx

    (Union[int, List[int]], default: 0 ) –

    The index (or indices) to apply the given signal to. Can either be an integer (single index to set) or an iterable of integers (e.g. a list of indices). For every integer of the iterable the signal value of the corresponding port index is set to the given new_signal. Defaults to 0.

Example

from netlist_carpentry.utils.gate_factory import and_gate module = Module(name='m') a = module.create_port('a', 'input', width=6) instance = and_gate(module, 'inst', A=a)

This sets the value of bit 0 of port A to HIGH

instance.set('A', 1, 0) instance.ports['A'].signal_str 'xxxxx1'

This sets the value of bits 1, 3 and 5 of port A to LOW, leaving the other bits as they already are.

instance.set('A', 0, [1, 3, 5]) instance.ports['A'].signal_str '0x0x01'

get_result

get_result(s1: Signal, s2: Signal) -> Signal

Returns the result of this gate's operation for given Signals s1 and s2.

This method is only implemented for bitwise evaluating gates (e.g. AndGate, OrGate). This method raises an UnsupportedOperationError if used on other gates (e.g. Adder).

For vector-level operations on full signal arrays, use :meth:get_result_vector instead.

Parameters:

  • s1

    (Signal) –

    The first Signal, i.e. the first operand.

  • s2

    (Signal) –

    The second Signal, i.e. the second operand.

Raises:

Returns:

  • Signal ( Signal ) –

    The result of this gate's operation on the given signals.

signals_in

signals_in(idx: NonNegativeInt = 0) -> Tuple[Signal, Signal]

The input signals of the gate.

Returns:

signal_out

signal_out(idx: NonNegativeInt = 0) -> Signal

The output signal of the gate.

Returns:

  • Signal ( Signal ) –

    The output signal of the gate.

GreaterEqual

Bases: BinaryNto1Gate, BaseModel

A GREATER-OR-EQUAL gate.

A GREATER-OR-EQUAL gate is a gate that produces a HIGH output signal if its "left" input signal value is greater or equal to its "right" input signal. Otherwise, it produces a LOW output signal.

Methods:

  • change_mutability

    Change the mutability status of this instance and optionally its ports.

  • evaluate

    Evaluates the gate's output signal based on its input signals.

  • all_connections

    Returns a dictionary mapping port names to their corresponding connection paths.

  • model_post_init

    Initializes the gate's ports and connections.

  • connect

    Add connections to the specified port of this instance.

  • disconnect

    Remove an existing connection from a specified port of this instance.

  • get_connection

    Retrieve the connection path associated with a specified port and bit index.

  • modify_connection

    Modify an existing connection within a specified port of this instance.

  • connect_modify

    Add a new connection or modify an existing one within the specified port of this instance.

  • tie_port

    Set a constant signal value for the specified port and bit index.

  • has_tied_ports

    Checks the ports of this instance whether any are tied to constant values.

  • has_tied_inputs

    Checks the input ports of this instance whether any are tied to constant values.

  • has_tied_outputs

    Checks the output ports of this instance whether any are tied to constant values.

  • update_signedness

    Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

  • split

    Performs a bit-wise split on this instance.

  • p2v

    Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

  • ps2v

    Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

  • set

    Sets the signal on a port.

  • get_result

    Returns the result of this gate's operation for given Signals s1 and s2.

  • signals_in

    The input signals of the gate.

  • signal_out

    The output signal of the gate.

Attributes:

name instance-attribute

name: str

The name of the element.

!!! Do not modify this variable after instantiating it. Use NetlistElement.set_name() instead. Modifying this variable might lead to inconsistencies later on.

metadata class-attribute instance-attribute

Metadata of a netlist element.

Can be user-defined, or e. g. by Yosys (such as src for the HDL source). Is also grouped by categories, i.e. all metadata from Yosys can be accessed via Module.metadata["yosys"], or via Module.metadata.yosys, which both return a dictionary of all metadata. Read the documentation of MetaDataMixin for more information.

path property

Returns the InstancePath of the netlist element.

The InstancePath object is constructed using the element's type and its raw hierarchical path.

Returns:

  • InstancePath ( InstancePath ) –

    The hierarchical path of the netlist element.

type property

type: EType

The type of the element, which is an instance.

hierarchy_level property

hierarchy_level: int

The level of hierarchy of the element in the design.

The hierarchy level is the number of separators in the element's raw path. For example, a top-level instance has a hierarchy level of 0, while a direct submodule instance has a hierarchy level of 1.

Returns:

  • int ( int ) –

    The hierarchy level of the element.

has_parent property

has_parent: bool

Whether this object has a parent.

circuit property

circuit: 'Circuit'

The circuit object to which this netlist element belongs to.

  • For a module, returns the circuit to which the module belongs.
  • For any other netlist element, recursively returns the circuit of the parent, which ultimately leads to a module, to which the netlist element belongs.

Raises:

  • ParentNotFoundError

    If a parent cannot be resolved somewhere in the hierarchical chain.

  • ObjectNotFoundError

    If for a module no circuit is set.

has_circuit property

has_circuit: bool

Whether this netlist element has a defined circuit it belongs to.

Tries to access self.circuit and returns whether the call was successful. Can be used instead of a try-except clause around the call to NetlistElement.circuit.

locked property

locked: bool

True if this NetlistElement instance is locked (i.e. it is currently structurally unchangeable), False if it is mutable.

Can be changed via NetlistElement.change_mutability(bool).

Immutability is used to prevent accidental changes to the design.

is_placeholder_instance property

is_placeholder_instance: bool

A placeholder represents an element that does not have a specific path.

True if this NetlistElement instance represents a placeholder, False otherwise.

can_carry_signal property

can_carry_signal: bool

Whether this exact object is able to receive, pass or hold signal values.

True for ports (as they drive or receive values) and wires (as they pass the signals from driver to load ports) as well as their respective segments. False for instances and modules.

connections property

connections: Dict[str, Dict[int, WireSegmentPath]]

A dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port. Elements with no connection (i.e. the path is None) are excluded. In case these are needed, use Instance.get_connections() instead.

Example

{ 'port1': {1: WireSegmentPath('path/to/element1'), 2: WireSegmentPath('path/to/element2')}, 'port2': {1: WireSegmentPath('path/to/element3')} }

connection_str_paths property

connection_str_paths: Dict[str, Dict[int, str]]

Returns a dictionary mapping port names to their corresponding connection paths as strings.

The keys are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are the raw string paths.

Example

{ 'port1': {0: 'path.to.element1', 1: 'path.to.element2'}, 'port2': {0: 'path.to.element3'} }

ports property

A dictionary mapping port names to their corresponding Port objects.

The keys of the dictionary are the names of the ports. The values are Port objects representing the ports.

Returns:

input_ports property

input_ports: Tuple[Port[Instance], Port[Instance]]

The input ports of the gate as a 2-tuple.

output_ports property

output_ports: Tuple[Port[Instance], ...]

Returns a tuple of output ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as outputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the output ports.

has_unconnected_port_segments property

has_unconnected_port_segments: bool

Returns True if the instance has at least one unconnected port segment.

signals property

signals: Dict[str, SignalArray]

A dictionary with all signals currently present on all ports of this instance.

is_blackbox property

is_blackbox: bool

Flag indicating whether the instance represents neither a primitive element nor a module instance.

If True, this instance does not have a module definition, and is also not a basic component (i.e. a primitive gate instance) from the internal gate library, such as a gate or flip-flop.

y_width property

y_width: PositiveInt

Width of the gate, which is always 1 for gates that reduce N-bit inputs to 1 bit.

a_width property

a_width: PositiveInt

Width of the gate's A port.

b_width property

b_width: PositiveInt

Width of the gate's B port.

is_combinational property

is_combinational: bool

Whether instances of this gate are considered combinational gates.

True for combinational gates, such as AND gates or arithmetic gates. False for flip-flops and latches.

is_sequential property

is_sequential: bool

Whether instances of this gate are considered sequential gates.

False for combinational gates, such as AND gates or arithmetic gates. True for flip-flops and latches.

output_port property

output_port: Port[Instance]

The output port of the gate.

data_width property

data_width: int

The data width of this instance.

Defaults to the data width of the output port. Can be overwritten in extended classes.

In contrast to self.width, which is used for the creation and initialization, this property is linked to the data width of the output port. This property is useful when the data width of the output port can be changed.

a_signed property

a_signed: bool

The signedness of input port A.

b_signed property

b_signed: bool

The signedness of input port B.

truth_table property

truth_table: Dict[Tuple[Signal, Signal], Signal]

A simple truth table as a dictionary.

This dictionary contains the input-output mapping for unary gates that evaluate bitwise (e.g. AndGate, OrGate). Not implemented for arithmetic gates (e.g. Adder).

change_mutability

change_mutability(is_now_locked: bool, recursive: bool = False) -> Self

Change the mutability status of this instance and optionally its ports.

This method allows setting whether this instance can be modified or not. If recursive is set to True, it also applies the same mutability status to all ports of this instance.

Parameters:

  • is_now_locked

    (bool) –

    The new mutability status for this instance.

  • recursive

    (bool, default: False ) –

    Whether to apply the change recursively to its ports. Defaults to False.

evaluate

evaluate() -> None

Evaluates the gate's output signal based on its input signals.

This method is called when the gate's input signals change, and it updates the gate's output signal accordingly.

all_connections

all_connections(
    include_unconnected: bool,
) -> Dict[str, Dict[int, WireSegmentPath]]

Returns a dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port.

Parameters:

  • include_unconnected

    (bool) –

    Whether to include unconnected ports in the result.

Returns:

model_post_init

model_post_init(__context: object) -> None

Initializes the gate's ports and connections.

This method is called after the gate's attributes have been initialized, and it sets up the gate's ports and connections.

connect

connect(
    port_name: str,
    ws_path: Optional[WireSegmentPath],
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add connections to the specified port of this instance.

This method can establish multiple connections if a range of indices is provided.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection(s) should be established.

  • ws_path

    (Optional[WireSegmentPath]) –

    The path of the wire segment that will be connected to this port. If None, the associated port (segment) remains unconnected.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

Raises:

  • ObjectLockedError

    If this instance is currently locked, and no connection can be made.

disconnect

disconnect(port_name: str, index: Optional[int] = None) -> None

Remove an existing connection from a specified port of this instance.

This method disconnects the wire segment at the given index within the specified port_name.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be removed.

  • index

    (Optional[int], default: None ) –

    The bit index within the port for this disconnection. Defaults to None, which completely disconnects the port.

Raises:

get_connection

get_connection(
    port_name: str, index: Optional[NonNegativeInt] = None
) -> Union[WireSegmentPath, Dict[int, WireSegmentPath], None]

Retrieve the connection path associated with a specified port and bit index.

If index is provided, this method returns the wire segment path connected to that specific bit within the port. Otherwise, it returns all connections for the given port as a dictionary mapping indices to WireSegmentPaths.

Parameters:

  • port_name

    (str) –

    The name of the port for which to retrieve the connection(s).

  • index

    (Optional[NonNegativeInt], default: None ) –

    The bit index within the port. Defaults to None.

Returns:

modify_connection

modify_connection(
    port_name: str, ws_path: WireSegmentPath, index: NonNegativeInt = 0
) -> None

Modify an existing connection within a specified port of this instance.

This method updates the wire segment path at the given index within the specified port_name. If the index does not exist yet, it is newly added, changing the width of the port.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be modified.

  • ws_path

    (WireSegmentPath) –

    The new wire segment path for this connection.

  • index

    (NonNegativeInt, default: 0 ) –

    The bit index within the port. Defaults to 0.

connect_modify

connect_modify(
    port_name: str,
    ws_path: WireSegmentPath,
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add a new connection or modify an existing one within the specified port of this instance.

If the connection already exists at the given index and port_name, it will be modified. Otherwise, a new connection is added.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be established or updated.

  • ws_path

    (WireSegmentPath) –

    The path of the wire segment that will be connected to this port.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

tie_port

tie_port(name: str, index: NonNegativeInt, sig_value: LogicLevel) -> None

Set a constant signal value for the specified port and bit index.

If the specified port does not exist, an error message is logged and the function returns False. Otherwise, the method tries to set the constant signal value for that port and returns True if successful.

Does not work for instance output ports, as they are always driven by their parent instances.

Parameters:

  • name

    (str) –

    The name of the port.

  • index

    (NonNegativeInt) –

    The bit index within the port.

  • sig_value

    (LogicLevel) –

    The constant signal value to be set ('0', '1', or 'Z').

Raises:

  • ObjectNotFoundError

    If no such port or port segment exists.

  • AlreadyConnectedError

    (raised by: PortSegment.tie_signal) If this segment is belongs to a load port and is already connected to a wire, from which it receives its value.

  • InvalidDirectionError

    (raised by: PortSegment.tie_signal) If this port segment belongs to an instance output port, which is driven by the instance inputs and the instance's internal logic.

  • InvalidSignalError

    (raised by: PortSegment.tie_signal) If an invalid value is provided.

has_tied_ports

has_tied_ports() -> bool

Checks the ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any ports of this instance are tied to constant values. False otherwise, i.e. all ports are connected to wires.

has_tied_inputs

has_tied_inputs() -> bool

Checks the input ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any input ports of this instance are tied to constant values. False otherwise, i.e. all input ports are connected to wires.

has_tied_outputs

has_tied_outputs() -> bool

Checks the output ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any output ports of this instance are tied to constant values. False otherwise, i.e. all output ports are connected to wires.

update_signedness

update_signedness(port_name: str) -> None

Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

Parameters:

  • port_name

    (str) –

    The name of the port, of which the signedness value is retrieved.

split

split() -> Dict[NonNegativeInt, Self]

Performs a bit-wise split on this instance.

If this instance supports splitting and has a data width of n bit, this method splits this instance into n 1-bit instances. This works for instances, where each output bit depends only on the corresponding input bit(s), e.g. an AND gate or a D-Flipflop.

Returns:

  • Dict[NonNegativeInt, Self]

    Dict[int, Instance]: An n-bit large dictionary, where each key conforms to a bit of the original instance, and each value is an 1-bit instance representing the corresponding "slice" of the original instance.

Raises:

  • SplittingUnsupportedError

    If this instance does not support splitting. Happens for any gate or instance whose behavior depends on the whole bus, and splitting would make it lose its meaning.

p2v

p2v(
    port: ANY_PORT,
    exclude_indices: Optional[List[int]] = None,
    include_indices: Optional[List[int]] = None,
) -> str

Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a Port object and converts them to their corresponding Verilog signal structure (p2v -> Port to Verilog signal syntax). For each segment of the port, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port is set to a constant, the corresponding constant wire segment placeholder is used instead. Port segments can be excluded from the conversion by providing a list of indices to the exclude_indices parameter, indicating which segments should be excluded from the conversion (e.g. segments that are known to be unconnected). Vice versa, only a certain subset of the port's segments may be converted to Verilog syntax, if include_indices is a given list of port indices. All indices not present in the list will be excluded from the conversion.

Parameters:

  • port

    (Port) –

    The Port object to convert.

  • exclude_indices

    (List[int], default: None ) –

    A list of indices to exclude from the conversion. Defaults to None.

  • include_indices

    (List[int], default: None ) –

    A list of indices (i.e. port slices) to include only for the conversion. Defaults to None.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

  • ObjectNotFoundError

    If the wire connected to a certain port segment could not be found.

  • UnsupportedOperationError

    If both exclude_indices and include_indices are specified. Only one of both may be given when calling this method.

ps2v

Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a PortSegment dictionary and converts them to their corresponding Verilog signal structure (ps2v -> PortSegment to Verilog signal syntax). For each segment, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port segment is set to a constant, the corresponding constant wire segment placeholder is used instead.

Parameters:

  • ps_dict

    (Dict[int, PortSegment]) –

    The PortSegment dictionary to convert. Each key (int) conforms to the index of the associated PortSegment object.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

set

set(
    port_name: str,
    new_signal: SignalOrLogicLevel,
    idx: Union[int, List[int]] = 0,
) -> None

Sets the signal on a port.

Parameters:

  • port_name

    (str) –

    The name of the port to set the signal on.

  • new_signal

    (Signal) –

    The new signal value.

  • idx

    (Union[int, List[int]], default: 0 ) –

    The index (or indices) to apply the given signal to. Can either be an integer (single index to set) or an iterable of integers (e.g. a list of indices). For every integer of the iterable the signal value of the corresponding port index is set to the given new_signal. Defaults to 0.

Example

from netlist_carpentry.utils.gate_factory import and_gate module = Module(name='m') a = module.create_port('a', 'input', width=6) instance = and_gate(module, 'inst', A=a)

This sets the value of bit 0 of port A to HIGH

instance.set('A', 1, 0) instance.ports['A'].signal_str 'xxxxx1'

This sets the value of bits 1, 3 and 5 of port A to LOW, leaving the other bits as they already are.

instance.set('A', 0, [1, 3, 5]) instance.ports['A'].signal_str '0x0x01'

get_result

get_result(s1: Signal, s2: Signal) -> Signal

Returns the result of this gate's operation for given Signals s1 and s2.

This method is only implemented for bitwise evaluating gates (e.g. AndGate, OrGate). This method raises an UnsupportedOperationError if used on other gates (e.g. Adder).

For vector-level operations on full signal arrays, use :meth:get_result_vector instead.

Parameters:

  • s1

    (Signal) –

    The first Signal, i.e. the first operand.

  • s2

    (Signal) –

    The second Signal, i.e. the second operand.

Raises:

Returns:

  • Signal ( Signal ) –

    The result of this gate's operation on the given signals.

signals_in

signals_in(idx: NonNegativeInt = 0) -> Tuple[Signal, Signal]

The input signals of the gate.

Returns:

signal_out

signal_out(idx: NonNegativeInt = 0) -> Signal

The output signal of the gate.

Returns:

  • Signal ( Signal ) –

    The output signal of the gate.

Multiplexer

Bases: NtoOneGate

A multiplexer.

A multiplexer is a gate that selects one of its input signals to be its output signal, based on a control signal.

Methods:

  • change_mutability

    Change the mutability status of this instance and optionally its ports.

  • evaluate

    Evaluates the gate's output signal based on its input signals.

  • all_connections

    Returns a dictionary mapping port names to their corresponding connection paths.

  • connect

    Add connections to the specified port of this instance.

  • disconnect

    Remove an existing connection from a specified port of this instance.

  • get_connection

    Retrieve the connection path associated with a specified port and bit index.

  • modify_connection

    Modify an existing connection within a specified port of this instance.

  • connect_modify

    Add a new connection or modify an existing one within the specified port of this instance.

  • tie_port

    Set a constant signal value for the specified port and bit index.

  • has_tied_ports

    Checks the ports of this instance whether any are tied to constant values.

  • has_tied_inputs

    Checks the input ports of this instance whether any are tied to constant values.

  • has_tied_outputs

    Checks the output ports of this instance whether any are tied to constant values.

  • update_signedness

    Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

  • split

    Performs a bit-wise split on this instance.

  • p2v

    Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

  • ps2v

    Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

  • set

    Sets the signal on a port.

Attributes:

name instance-attribute

name: str

The name of the element.

!!! Do not modify this variable after instantiating it. Use NetlistElement.set_name() instead. Modifying this variable might lead to inconsistencies later on.

metadata class-attribute instance-attribute

Metadata of a netlist element.

Can be user-defined, or e. g. by Yosys (such as src for the HDL source). Is also grouped by categories, i.e. all metadata from Yosys can be accessed via Module.metadata["yosys"], or via Module.metadata.yosys, which both return a dictionary of all metadata. Read the documentation of MetaDataMixin for more information.

path property

Returns the InstancePath of the netlist element.

The InstancePath object is constructed using the element's type and its raw hierarchical path.

Returns:

  • InstancePath ( InstancePath ) –

    The hierarchical path of the netlist element.

type property

type: EType

The type of the element, which is an instance.

hierarchy_level property

hierarchy_level: int

The level of hierarchy of the element in the design.

The hierarchy level is the number of separators in the element's raw path. For example, a top-level instance has a hierarchy level of 0, while a direct submodule instance has a hierarchy level of 1.

Returns:

  • int ( int ) –

    The hierarchy level of the element.

has_parent property

has_parent: bool

Whether this object has a parent.

circuit property

circuit: 'Circuit'

The circuit object to which this netlist element belongs to.

  • For a module, returns the circuit to which the module belongs.
  • For any other netlist element, recursively returns the circuit of the parent, which ultimately leads to a module, to which the netlist element belongs.

Raises:

  • ParentNotFoundError

    If a parent cannot be resolved somewhere in the hierarchical chain.

  • ObjectNotFoundError

    If for a module no circuit is set.

has_circuit property

has_circuit: bool

Whether this netlist element has a defined circuit it belongs to.

Tries to access self.circuit and returns whether the call was successful. Can be used instead of a try-except clause around the call to NetlistElement.circuit.

locked property

locked: bool

True if this NetlistElement instance is locked (i.e. it is currently structurally unchangeable), False if it is mutable.

Can be changed via NetlistElement.change_mutability(bool).

Immutability is used to prevent accidental changes to the design.

is_placeholder_instance property

is_placeholder_instance: bool

A placeholder represents an element that does not have a specific path.

True if this NetlistElement instance represents a placeholder, False otherwise.

can_carry_signal property

can_carry_signal: bool

Whether this exact object is able to receive, pass or hold signal values.

True for ports (as they drive or receive values) and wires (as they pass the signals from driver to load ports) as well as their respective segments. False for instances and modules.

connections property

connections: Dict[str, Dict[int, WireSegmentPath]]

A dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port. Elements with no connection (i.e. the path is None) are excluded. In case these are needed, use Instance.get_connections() instead.

Example

{ 'port1': {1: WireSegmentPath('path/to/element1'), 2: WireSegmentPath('path/to/element2')}, 'port2': {1: WireSegmentPath('path/to/element3')} }

connection_str_paths property

connection_str_paths: Dict[str, Dict[int, str]]

Returns a dictionary mapping port names to their corresponding connection paths as strings.

The keys are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are the raw string paths.

Example

{ 'port1': {0: 'path.to.element1', 1: 'path.to.element2'}, 'port2': {0: 'path.to.element3'} }

ports property

A dictionary mapping port names to their corresponding Port objects.

The keys of the dictionary are the names of the ports. The values are Port objects representing the ports.

Returns:

input_ports property

input_ports: Tuple[Port[Instance], ...]

Returns a tuple of input ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as inputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the input ports.

output_ports property

output_ports: Tuple[Port[Instance], ...]

Returns a tuple of output ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as outputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the output ports.

has_unconnected_port_segments property

has_unconnected_port_segments: bool

Returns True if the instance has at least one unconnected port segment.

signals property

signals: Dict[str, SignalArray]

A dictionary with all signals currently present on all ports of this instance.

is_blackbox property

is_blackbox: bool

Flag indicating whether the instance represents neither a primitive element nor a module instance.

If True, this instance does not have a module definition, and is also not a basic component (i.e. a primitive gate instance) from the internal gate library, such as a gate or flip-flop.

y_width property writable

y_width: PositiveInt

Width of the output/data port.

a_width property

a_width: PositiveInt

Width of the gate's A port.

b_width property

b_width: PositiveInt

Width of the gate's B port.

is_combinational property

is_combinational: bool

Whether instances of this gate are considered combinational gates.

True for combinational gates, such as AND gates or arithmetic gates. False for flip-flops and latches.

is_sequential property

is_sequential: bool

Whether instances of this gate are considered sequential gates.

False for combinational gates, such as AND gates or arithmetic gates. True for flip-flops and latches.

data_width property

data_width: int

The data width of this instance.

Defaults to the data width of the output port. Can be overwritten in extended classes.

In contrast to self.width, which is used for the creation and initialization, this property is linked to the data width of the output port. This property is useful when the data width of the output port can be changed.

bit_width property writable

bit_width: int

Width of the select/control signal.

s_defined property

s_defined: bool

Whether all select signal bits are defined.

s_val property

s_val: int

Integer value of the select signals, or -1 if undefined.

s_port property

s_port: Port[Instance]

The select/control port.

active_input property

active_input: Optional[Port[Instance]]

The active input port based on select value.

change_mutability

change_mutability(is_now_locked: bool, recursive: bool = False) -> Self

Change the mutability status of this instance and optionally its ports.

This method allows setting whether this instance can be modified or not. If recursive is set to True, it also applies the same mutability status to all ports of this instance.

Parameters:

  • is_now_locked

    (bool) –

    The new mutability status for this instance.

  • recursive

    (bool, default: False ) –

    Whether to apply the change recursively to its ports. Defaults to False.

evaluate

evaluate() -> None

Evaluates the gate's output signal based on its input signals.

This method is called when the gate's input signals change, and it updates the gate's output signal accordingly.

all_connections

all_connections(
    include_unconnected: bool,
) -> Dict[str, Dict[int, WireSegmentPath]]

Returns a dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port.

Parameters:

  • include_unconnected

    (bool) –

    Whether to include unconnected ports in the result.

Returns:

connect

connect(
    port_name: str,
    ws_path: Optional[WireSegmentPath],
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add connections to the specified port of this instance.

This method can establish multiple connections if a range of indices is provided.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection(s) should be established.

  • ws_path

    (Optional[WireSegmentPath]) –

    The path of the wire segment that will be connected to this port. If None, the associated port (segment) remains unconnected.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

Raises:

  • ObjectLockedError

    If this instance is currently locked, and no connection can be made.

disconnect

disconnect(port_name: str, index: Optional[int] = None) -> None

Remove an existing connection from a specified port of this instance.

This method disconnects the wire segment at the given index within the specified port_name.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be removed.

  • index

    (Optional[int], default: None ) –

    The bit index within the port for this disconnection. Defaults to None, which completely disconnects the port.

Raises:

get_connection

get_connection(
    port_name: str, index: Optional[NonNegativeInt] = None
) -> Union[WireSegmentPath, Dict[int, WireSegmentPath], None]

Retrieve the connection path associated with a specified port and bit index.

If index is provided, this method returns the wire segment path connected to that specific bit within the port. Otherwise, it returns all connections for the given port as a dictionary mapping indices to WireSegmentPaths.

Parameters:

  • port_name

    (str) –

    The name of the port for which to retrieve the connection(s).

  • index

    (Optional[NonNegativeInt], default: None ) –

    The bit index within the port. Defaults to None.

Returns:

modify_connection

modify_connection(
    port_name: str, ws_path: WireSegmentPath, index: NonNegativeInt = 0
) -> None

Modify an existing connection within a specified port of this instance.

This method updates the wire segment path at the given index within the specified port_name. If the index does not exist yet, it is newly added, changing the width of the port.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be modified.

  • ws_path

    (WireSegmentPath) –

    The new wire segment path for this connection.

  • index

    (NonNegativeInt, default: 0 ) –

    The bit index within the port. Defaults to 0.

connect_modify

connect_modify(
    port_name: str,
    ws_path: WireSegmentPath,
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add a new connection or modify an existing one within the specified port of this instance.

If the connection already exists at the given index and port_name, it will be modified. Otherwise, a new connection is added.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be established or updated.

  • ws_path

    (WireSegmentPath) –

    The path of the wire segment that will be connected to this port.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

tie_port

tie_port(name: str, index: NonNegativeInt, sig_value: LogicLevel) -> None

Set a constant signal value for the specified port and bit index.

If the specified port does not exist, an error message is logged and the function returns False. Otherwise, the method tries to set the constant signal value for that port and returns True if successful.

Does not work for instance output ports, as they are always driven by their parent instances.

Parameters:

  • name

    (str) –

    The name of the port.

  • index

    (NonNegativeInt) –

    The bit index within the port.

  • sig_value

    (LogicLevel) –

    The constant signal value to be set ('0', '1', or 'Z').

Raises:

  • ObjectNotFoundError

    If no such port or port segment exists.

  • AlreadyConnectedError

    (raised by: PortSegment.tie_signal) If this segment is belongs to a load port and is already connected to a wire, from which it receives its value.

  • InvalidDirectionError

    (raised by: PortSegment.tie_signal) If this port segment belongs to an instance output port, which is driven by the instance inputs and the instance's internal logic.

  • InvalidSignalError

    (raised by: PortSegment.tie_signal) If an invalid value is provided.

has_tied_ports

has_tied_ports() -> bool

Checks the ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any ports of this instance are tied to constant values. False otherwise, i.e. all ports are connected to wires.

has_tied_inputs

has_tied_inputs() -> bool

Checks the input ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any input ports of this instance are tied to constant values. False otherwise, i.e. all input ports are connected to wires.

has_tied_outputs

has_tied_outputs() -> bool

Checks the output ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any output ports of this instance are tied to constant values. False otherwise, i.e. all output ports are connected to wires.

update_signedness

update_signedness(port_name: str) -> None

Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

Parameters:

  • port_name

    (str) –

    The name of the port, of which the signedness value is retrieved.

split

split() -> Dict[NonNegativeInt, Self]

Performs a bit-wise split on this instance.

If this instance supports splitting and has a data width of n bit, this method splits this instance into n 1-bit instances. This works for instances, where each output bit depends only on the corresponding input bit(s), e.g. an AND gate or a D-Flipflop.

Returns:

  • Dict[NonNegativeInt, Self]

    Dict[int, Instance]: An n-bit large dictionary, where each key conforms to a bit of the original instance, and each value is an 1-bit instance representing the corresponding "slice" of the original instance.

Raises:

  • SplittingUnsupportedError

    If this instance does not support splitting. Happens for any gate or instance whose behavior depends on the whole bus, and splitting would make it lose its meaning.

p2v

p2v(
    port: ANY_PORT,
    exclude_indices: Optional[List[int]] = None,
    include_indices: Optional[List[int]] = None,
) -> str

Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a Port object and converts them to their corresponding Verilog signal structure (p2v -> Port to Verilog signal syntax). For each segment of the port, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port is set to a constant, the corresponding constant wire segment placeholder is used instead. Port segments can be excluded from the conversion by providing a list of indices to the exclude_indices parameter, indicating which segments should be excluded from the conversion (e.g. segments that are known to be unconnected). Vice versa, only a certain subset of the port's segments may be converted to Verilog syntax, if include_indices is a given list of port indices. All indices not present in the list will be excluded from the conversion.

Parameters:

  • port

    (Port) –

    The Port object to convert.

  • exclude_indices

    (List[int], default: None ) –

    A list of indices to exclude from the conversion. Defaults to None.

  • include_indices

    (List[int], default: None ) –

    A list of indices (i.e. port slices) to include only for the conversion. Defaults to None.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

  • ObjectNotFoundError

    If the wire connected to a certain port segment could not be found.

  • UnsupportedOperationError

    If both exclude_indices and include_indices are specified. Only one of both may be given when calling this method.

ps2v

Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a PortSegment dictionary and converts them to their corresponding Verilog signal structure (ps2v -> PortSegment to Verilog signal syntax). For each segment, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port segment is set to a constant, the corresponding constant wire segment placeholder is used instead.

Parameters:

  • ps_dict

    (Dict[int, PortSegment]) –

    The PortSegment dictionary to convert. Each key (int) conforms to the index of the associated PortSegment object.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

set

set(
    port_name: str,
    new_signal: SignalOrLogicLevel,
    idx: Union[int, List[int]] = 0,
) -> None

Sets the signal on a port.

Parameters:

  • port_name

    (str) –

    The name of the port to set the signal on.

  • new_signal

    (Signal) –

    The new signal value.

  • idx

    (Union[int, List[int]], default: 0 ) –

    The index (or indices) to apply the given signal to. Can either be an integer (single index to set) or an iterable of integers (e.g. a list of indices). For every integer of the iterable the signal value of the corresponding port index is set to the given new_signal. Defaults to 0.

Example

from netlist_carpentry.utils.gate_factory import and_gate module = Module(name='m') a = module.create_port('a', 'input', width=6) instance = and_gate(module, 'inst', A=a)

This sets the value of bit 0 of port A to HIGH

instance.set('A', 1, 0) instance.ports['A'].signal_str 'xxxxx1'

This sets the value of bits 1, 3 and 5 of port A to LOW, leaving the other bits as they already are.

instance.set('A', 0, [1, 3, 5]) instance.ports['A'].signal_str '0x0x01'

Demultiplexer

Bases: OneToNGate

A demultiplexer.

A demultiplexer is a gate that selects one of its output ports to be connected to its input signal, based on a control signal.

Methods:

  • change_mutability

    Change the mutability status of this instance and optionally its ports.

  • evaluate

    Evaluates the gate's output signal based on its input signals.

  • all_connections

    Returns a dictionary mapping port names to their corresponding connection paths.

  • connect

    Add connections to the specified port of this instance.

  • disconnect

    Remove an existing connection from a specified port of this instance.

  • get_connection

    Retrieve the connection path associated with a specified port and bit index.

  • modify_connection

    Modify an existing connection within a specified port of this instance.

  • connect_modify

    Add a new connection or modify an existing one within the specified port of this instance.

  • tie_port

    Set a constant signal value for the specified port and bit index.

  • has_tied_ports

    Checks the ports of this instance whether any are tied to constant values.

  • has_tied_inputs

    Checks the input ports of this instance whether any are tied to constant values.

  • has_tied_outputs

    Checks the output ports of this instance whether any are tied to constant values.

  • update_signedness

    Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

  • split

    Performs a bit-wise split on this instance.

  • p2v

    Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

  • ps2v

    Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

  • set

    Sets the signal on a port.

Attributes:

name instance-attribute

name: str

The name of the element.

!!! Do not modify this variable after instantiating it. Use NetlistElement.set_name() instead. Modifying this variable might lead to inconsistencies later on.

metadata class-attribute instance-attribute

Metadata of a netlist element.

Can be user-defined, or e. g. by Yosys (such as src for the HDL source). Is also grouped by categories, i.e. all metadata from Yosys can be accessed via Module.metadata["yosys"], or via Module.metadata.yosys, which both return a dictionary of all metadata. Read the documentation of MetaDataMixin for more information.

path property

Returns the InstancePath of the netlist element.

The InstancePath object is constructed using the element's type and its raw hierarchical path.

Returns:

  • InstancePath ( InstancePath ) –

    The hierarchical path of the netlist element.

type property

type: EType

The type of the element, which is an instance.

hierarchy_level property

hierarchy_level: int

The level of hierarchy of the element in the design.

The hierarchy level is the number of separators in the element's raw path. For example, a top-level instance has a hierarchy level of 0, while a direct submodule instance has a hierarchy level of 1.

Returns:

  • int ( int ) –

    The hierarchy level of the element.

has_parent property

has_parent: bool

Whether this object has a parent.

circuit property

circuit: 'Circuit'

The circuit object to which this netlist element belongs to.

  • For a module, returns the circuit to which the module belongs.
  • For any other netlist element, recursively returns the circuit of the parent, which ultimately leads to a module, to which the netlist element belongs.

Raises:

  • ParentNotFoundError

    If a parent cannot be resolved somewhere in the hierarchical chain.

  • ObjectNotFoundError

    If for a module no circuit is set.

has_circuit property

has_circuit: bool

Whether this netlist element has a defined circuit it belongs to.

Tries to access self.circuit and returns whether the call was successful. Can be used instead of a try-except clause around the call to NetlistElement.circuit.

locked property

locked: bool

True if this NetlistElement instance is locked (i.e. it is currently structurally unchangeable), False if it is mutable.

Can be changed via NetlistElement.change_mutability(bool).

Immutability is used to prevent accidental changes to the design.

is_placeholder_instance property

is_placeholder_instance: bool

A placeholder represents an element that does not have a specific path.

True if this NetlistElement instance represents a placeholder, False otherwise.

can_carry_signal property

can_carry_signal: bool

Whether this exact object is able to receive, pass or hold signal values.

True for ports (as they drive or receive values) and wires (as they pass the signals from driver to load ports) as well as their respective segments. False for instances and modules.

connections property

connections: Dict[str, Dict[int, WireSegmentPath]]

A dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port. Elements with no connection (i.e. the path is None) are excluded. In case these are needed, use Instance.get_connections() instead.

Example

{ 'port1': {1: WireSegmentPath('path/to/element1'), 2: WireSegmentPath('path/to/element2')}, 'port2': {1: WireSegmentPath('path/to/element3')} }

connection_str_paths property

connection_str_paths: Dict[str, Dict[int, str]]

Returns a dictionary mapping port names to their corresponding connection paths as strings.

The keys are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are the raw string paths.

Example

{ 'port1': {0: 'path.to.element1', 1: 'path.to.element2'}, 'port2': {0: 'path.to.element3'} }

ports property

A dictionary mapping port names to their corresponding Port objects.

The keys of the dictionary are the names of the ports. The values are Port objects representing the ports.

Returns:

input_ports property

input_ports: Tuple[Port[Instance], ...]

Returns a tuple of input ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as inputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the input ports.

output_ports property

output_ports: Tuple[Port[Instance], ...]

Returns a tuple of output ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as outputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the output ports.

has_unconnected_port_segments property

has_unconnected_port_segments: bool

Returns True if the instance has at least one unconnected port segment.

signals property

signals: Dict[str, SignalArray]

A dictionary with all signals currently present on all ports of this instance.

is_blackbox property

is_blackbox: bool

Flag indicating whether the instance represents neither a primitive element nor a module instance.

If True, this instance does not have a module definition, and is also not a basic component (i.e. a primitive gate instance) from the internal gate library, such as a gate or flip-flop.

y_width property writable

y_width: PositiveInt

Width of the input/data port.

a_width property

a_width: PositiveInt

Width of the gate's A port.

b_width property

b_width: PositiveInt

Width of the gate's B port.

is_combinational property

is_combinational: bool

Whether instances of this gate are considered combinational gates.

True for combinational gates, such as AND gates or arithmetic gates. False for flip-flops and latches.

is_sequential property

is_sequential: bool

Whether instances of this gate are considered sequential gates.

False for combinational gates, such as AND gates or arithmetic gates. True for flip-flops and latches.

output_port property

output_port: Port[Instance]

The output port of the gate.

bit_width property writable

bit_width: int

Width of the select/control signal.

s_defined property

s_defined: bool

Whether all select signal bits are defined.

s_val property

s_val: int

Integer value of the select signals, or -1 if undefined.

active_output property

active_output: Optional[Port[Instance]]

The active output port based on select value.

s_port property

s_port: Port[Instance]

The select/control port.

change_mutability

change_mutability(is_now_locked: bool, recursive: bool = False) -> Self

Change the mutability status of this instance and optionally its ports.

This method allows setting whether this instance can be modified or not. If recursive is set to True, it also applies the same mutability status to all ports of this instance.

Parameters:

  • is_now_locked

    (bool) –

    The new mutability status for this instance.

  • recursive

    (bool, default: False ) –

    Whether to apply the change recursively to its ports. Defaults to False.

evaluate

evaluate() -> None

Evaluates the gate's output signal based on its input signals.

This method is called when the gate's input signals change, and it updates the gate's output signal accordingly.

all_connections

all_connections(
    include_unconnected: bool,
) -> Dict[str, Dict[int, WireSegmentPath]]

Returns a dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port.

Parameters:

  • include_unconnected

    (bool) –

    Whether to include unconnected ports in the result.

Returns:

connect

connect(
    port_name: str,
    ws_path: Optional[WireSegmentPath],
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add connections to the specified port of this instance.

This method can establish multiple connections if a range of indices is provided.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection(s) should be established.

  • ws_path

    (Optional[WireSegmentPath]) –

    The path of the wire segment that will be connected to this port. If None, the associated port (segment) remains unconnected.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

Raises:

  • ObjectLockedError

    If this instance is currently locked, and no connection can be made.

disconnect

disconnect(port_name: str, index: Optional[int] = None) -> None

Remove an existing connection from a specified port of this instance.

This method disconnects the wire segment at the given index within the specified port_name.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be removed.

  • index

    (Optional[int], default: None ) –

    The bit index within the port for this disconnection. Defaults to None, which completely disconnects the port.

Raises:

get_connection

get_connection(
    port_name: str, index: Optional[NonNegativeInt] = None
) -> Union[WireSegmentPath, Dict[int, WireSegmentPath], None]

Retrieve the connection path associated with a specified port and bit index.

If index is provided, this method returns the wire segment path connected to that specific bit within the port. Otherwise, it returns all connections for the given port as a dictionary mapping indices to WireSegmentPaths.

Parameters:

  • port_name

    (str) –

    The name of the port for which to retrieve the connection(s).

  • index

    (Optional[NonNegativeInt], default: None ) –

    The bit index within the port. Defaults to None.

Returns:

modify_connection

modify_connection(
    port_name: str, ws_path: WireSegmentPath, index: NonNegativeInt = 0
) -> None

Modify an existing connection within a specified port of this instance.

This method updates the wire segment path at the given index within the specified port_name. If the index does not exist yet, it is newly added, changing the width of the port.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be modified.

  • ws_path

    (WireSegmentPath) –

    The new wire segment path for this connection.

  • index

    (NonNegativeInt, default: 0 ) –

    The bit index within the port. Defaults to 0.

connect_modify

connect_modify(
    port_name: str,
    ws_path: WireSegmentPath,
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add a new connection or modify an existing one within the specified port of this instance.

If the connection already exists at the given index and port_name, it will be modified. Otherwise, a new connection is added.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be established or updated.

  • ws_path

    (WireSegmentPath) –

    The path of the wire segment that will be connected to this port.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

tie_port

tie_port(name: str, index: NonNegativeInt, sig_value: LogicLevel) -> None

Set a constant signal value for the specified port and bit index.

If the specified port does not exist, an error message is logged and the function returns False. Otherwise, the method tries to set the constant signal value for that port and returns True if successful.

Does not work for instance output ports, as they are always driven by their parent instances.

Parameters:

  • name

    (str) –

    The name of the port.

  • index

    (NonNegativeInt) –

    The bit index within the port.

  • sig_value

    (LogicLevel) –

    The constant signal value to be set ('0', '1', or 'Z').

Raises:

  • ObjectNotFoundError

    If no such port or port segment exists.

  • AlreadyConnectedError

    (raised by: PortSegment.tie_signal) If this segment is belongs to a load port and is already connected to a wire, from which it receives its value.

  • InvalidDirectionError

    (raised by: PortSegment.tie_signal) If this port segment belongs to an instance output port, which is driven by the instance inputs and the instance's internal logic.

  • InvalidSignalError

    (raised by: PortSegment.tie_signal) If an invalid value is provided.

has_tied_ports

has_tied_ports() -> bool

Checks the ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any ports of this instance are tied to constant values. False otherwise, i.e. all ports are connected to wires.

has_tied_inputs

has_tied_inputs() -> bool

Checks the input ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any input ports of this instance are tied to constant values. False otherwise, i.e. all input ports are connected to wires.

has_tied_outputs

has_tied_outputs() -> bool

Checks the output ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any output ports of this instance are tied to constant values. False otherwise, i.e. all output ports are connected to wires.

update_signedness

update_signedness(port_name: str) -> None

Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

Parameters:

  • port_name

    (str) –

    The name of the port, of which the signedness value is retrieved.

split

split() -> Dict[NonNegativeInt, Self]

Performs a bit-wise split on this instance.

If this instance supports splitting and has a data width of n bit, this method splits this instance into n 1-bit instances. This works for instances, where each output bit depends only on the corresponding input bit(s), e.g. an AND gate or a D-Flipflop.

Returns:

  • Dict[NonNegativeInt, Self]

    Dict[int, Instance]: An n-bit large dictionary, where each key conforms to a bit of the original instance, and each value is an 1-bit instance representing the corresponding "slice" of the original instance.

Raises:

  • SplittingUnsupportedError

    If this instance does not support splitting. Happens for any gate or instance whose behavior depends on the whole bus, and splitting would make it lose its meaning.

p2v

p2v(
    port: ANY_PORT,
    exclude_indices: Optional[List[int]] = None,
    include_indices: Optional[List[int]] = None,
) -> str

Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a Port object and converts them to their corresponding Verilog signal structure (p2v -> Port to Verilog signal syntax). For each segment of the port, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port is set to a constant, the corresponding constant wire segment placeholder is used instead. Port segments can be excluded from the conversion by providing a list of indices to the exclude_indices parameter, indicating which segments should be excluded from the conversion (e.g. segments that are known to be unconnected). Vice versa, only a certain subset of the port's segments may be converted to Verilog syntax, if include_indices is a given list of port indices. All indices not present in the list will be excluded from the conversion.

Parameters:

  • port

    (Port) –

    The Port object to convert.

  • exclude_indices

    (List[int], default: None ) –

    A list of indices to exclude from the conversion. Defaults to None.

  • include_indices

    (List[int], default: None ) –

    A list of indices (i.e. port slices) to include only for the conversion. Defaults to None.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

  • ObjectNotFoundError

    If the wire connected to a certain port segment could not be found.

  • UnsupportedOperationError

    If both exclude_indices and include_indices are specified. Only one of both may be given when calling this method.

ps2v

Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a PortSegment dictionary and converts them to their corresponding Verilog signal structure (ps2v -> PortSegment to Verilog signal syntax). For each segment, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port segment is set to a constant, the corresponding constant wire segment placeholder is used instead.

Parameters:

  • ps_dict

    (Dict[int, PortSegment]) –

    The PortSegment dictionary to convert. Each key (int) conforms to the index of the associated PortSegment object.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

set

set(
    port_name: str,
    new_signal: SignalOrLogicLevel,
    idx: Union[int, List[int]] = 0,
) -> None

Sets the signal on a port.

Parameters:

  • port_name

    (str) –

    The name of the port to set the signal on.

  • new_signal

    (Signal) –

    The new signal value.

  • idx

    (Union[int, List[int]], default: 0 ) –

    The index (or indices) to apply the given signal to. Can either be an integer (single index to set) or an iterable of integers (e.g. a list of indices). For every integer of the iterable the signal value of the corresponding port index is set to the given new_signal. Defaults to 0.

Example

from netlist_carpentry.utils.gate_factory import and_gate module = Module(name='m') a = module.create_port('a', 'input', width=6) instance = and_gate(module, 'inst', A=a)

This sets the value of bit 0 of port A to HIGH

instance.set('A', 1, 0) instance.ports['A'].signal_str 'xxxxx1'

This sets the value of bits 1, 3 and 5 of port A to LOW, leaving the other bits as they already are.

instance.set('A', 0, [1, 3, 5]) instance.ports['A'].signal_str '0x0x01'

Exponentiator

Bases: ArithmeticGate, BaseModel

Methods:

  • change_mutability

    Change the mutability status of this instance and optionally its ports.

  • evaluate

    Evaluates the gate's output signal based on its input signals.

  • all_connections

    Returns a dictionary mapping port names to their corresponding connection paths.

  • model_post_init

    Initializes the gate's ports and connections.

  • connect

    Add connections to the specified port of this instance.

  • disconnect

    Remove an existing connection from a specified port of this instance.

  • get_connection

    Retrieve the connection path associated with a specified port and bit index.

  • modify_connection

    Modify an existing connection within a specified port of this instance.

  • connect_modify

    Add a new connection or modify an existing one within the specified port of this instance.

  • tie_port

    Set a constant signal value for the specified port and bit index.

  • has_tied_ports

    Checks the ports of this instance whether any are tied to constant values.

  • has_tied_inputs

    Checks the input ports of this instance whether any are tied to constant values.

  • has_tied_outputs

    Checks the output ports of this instance whether any are tied to constant values.

  • update_signedness

    Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

  • split

    Performs a bit-wise split on this instance.

  • p2v

    Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

  • ps2v

    Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

  • set

    Sets the signal on a port.

  • get_result

    Returns the result of this gate's operation for given Signals s1 and s2.

  • signals_in

    The input signals of the gate.

  • signal_out

    The output signal of the gate.

Attributes:

name instance-attribute

name: str

The name of the element.

!!! Do not modify this variable after instantiating it. Use NetlistElement.set_name() instead. Modifying this variable might lead to inconsistencies later on.

metadata class-attribute instance-attribute

Metadata of a netlist element.

Can be user-defined, or e. g. by Yosys (such as src for the HDL source). Is also grouped by categories, i.e. all metadata from Yosys can be accessed via Module.metadata["yosys"], or via Module.metadata.yosys, which both return a dictionary of all metadata. Read the documentation of MetaDataMixin for more information.

path property

Returns the InstancePath of the netlist element.

The InstancePath object is constructed using the element's type and its raw hierarchical path.

Returns:

  • InstancePath ( InstancePath ) –

    The hierarchical path of the netlist element.

type property

type: EType

The type of the element, which is an instance.

hierarchy_level property

hierarchy_level: int

The level of hierarchy of the element in the design.

The hierarchy level is the number of separators in the element's raw path. For example, a top-level instance has a hierarchy level of 0, while a direct submodule instance has a hierarchy level of 1.

Returns:

  • int ( int ) –

    The hierarchy level of the element.

has_parent property

has_parent: bool

Whether this object has a parent.

circuit property

circuit: 'Circuit'

The circuit object to which this netlist element belongs to.

  • For a module, returns the circuit to which the module belongs.
  • For any other netlist element, recursively returns the circuit of the parent, which ultimately leads to a module, to which the netlist element belongs.

Raises:

  • ParentNotFoundError

    If a parent cannot be resolved somewhere in the hierarchical chain.

  • ObjectNotFoundError

    If for a module no circuit is set.

has_circuit property

has_circuit: bool

Whether this netlist element has a defined circuit it belongs to.

Tries to access self.circuit and returns whether the call was successful. Can be used instead of a try-except clause around the call to NetlistElement.circuit.

locked property

locked: bool

True if this NetlistElement instance is locked (i.e. it is currently structurally unchangeable), False if it is mutable.

Can be changed via NetlistElement.change_mutability(bool).

Immutability is used to prevent accidental changes to the design.

is_placeholder_instance property

is_placeholder_instance: bool

A placeholder represents an element that does not have a specific path.

True if this NetlistElement instance represents a placeholder, False otherwise.

can_carry_signal property

can_carry_signal: bool

Whether this exact object is able to receive, pass or hold signal values.

True for ports (as they drive or receive values) and wires (as they pass the signals from driver to load ports) as well as their respective segments. False for instances and modules.

connections property

connections: Dict[str, Dict[int, WireSegmentPath]]

A dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port. Elements with no connection (i.e. the path is None) are excluded. In case these are needed, use Instance.get_connections() instead.

Example

{ 'port1': {1: WireSegmentPath('path/to/element1'), 2: WireSegmentPath('path/to/element2')}, 'port2': {1: WireSegmentPath('path/to/element3')} }

connection_str_paths property

connection_str_paths: Dict[str, Dict[int, str]]

Returns a dictionary mapping port names to their corresponding connection paths as strings.

The keys are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are the raw string paths.

Example

{ 'port1': {0: 'path.to.element1', 1: 'path.to.element2'}, 'port2': {0: 'path.to.element3'} }

ports property

A dictionary mapping port names to their corresponding Port objects.

The keys of the dictionary are the names of the ports. The values are Port objects representing the ports.

Returns:

input_ports property

input_ports: Tuple[Port[Instance], Port[Instance]]

The input ports of the gate.

Returns:

output_ports property

output_ports: Tuple[Port[Instance], ...]

Returns a tuple of output ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as outputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the output ports.

has_unconnected_port_segments property

has_unconnected_port_segments: bool

Returns True if the instance has at least one unconnected port segment.

signals property

signals: Dict[str, SignalArray]

A dictionary with all signals currently present on all ports of this instance.

is_blackbox property

is_blackbox: bool

Flag indicating whether the instance represents neither a primitive element nor a module instance.

If True, this instance does not have a module definition, and is also not a basic component (i.e. a primitive gate instance) from the internal gate library, such as a gate or flip-flop.

y_width property

y_width: PositiveInt

Width of the gate, based on a certain port's width, depending on the actual gate.

a_width property

a_width: PositiveInt

Width of the gate's A port.

b_width property

b_width: PositiveInt

Width of the gate's B port.

is_combinational property

is_combinational: bool

Whether instances of this gate are considered combinational gates.

True for combinational gates, such as AND gates or arithmetic gates. False for flip-flops and latches.

is_sequential property

is_sequential: bool

Whether instances of this gate are considered sequential gates.

False for combinational gates, such as AND gates or arithmetic gates. True for flip-flops and latches.

output_port property

output_port: Port[Instance]

The output port of the gate.

Returns:

data_width property

data_width: int

The data width of this instance.

Defaults to the data width of the output port. Can be overwritten in extended classes.

In contrast to self.width, which is used for the creation and initialization, this property is linked to the data width of the output port. This property is useful when the data width of the output port can be changed.

a_signed property

a_signed: bool

The signedness of input port A.

b_signed property

b_signed: bool

The signedness of input port B.

truth_table property

truth_table: Dict[Tuple[Signal, Signal], Signal]

A simple truth table as a dictionary.

This dictionary contains the input-output mapping for unary gates that evaluate bitwise (e.g. AndGate, OrGate). Not implemented for arithmetic gates (e.g. Adder).

change_mutability

change_mutability(is_now_locked: bool, recursive: bool = False) -> Self

Change the mutability status of this instance and optionally its ports.

This method allows setting whether this instance can be modified or not. If recursive is set to True, it also applies the same mutability status to all ports of this instance.

Parameters:

  • is_now_locked

    (bool) –

    The new mutability status for this instance.

  • recursive

    (bool, default: False ) –

    Whether to apply the change recursively to its ports. Defaults to False.

evaluate

evaluate() -> None

Evaluates the gate's output signal based on its input signals.

This method is called when the gate's input signals change, and it updates the gate's output signal accordingly.

all_connections

all_connections(
    include_unconnected: bool,
) -> Dict[str, Dict[int, WireSegmentPath]]

Returns a dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port.

Parameters:

  • include_unconnected

    (bool) –

    Whether to include unconnected ports in the result.

Returns:

model_post_init

model_post_init(__context: object) -> None

Initializes the gate's ports and connections.

This method is called after the gate's attributes have been initialized, and it sets up the gate's ports and connections.

connect

connect(
    port_name: str,
    ws_path: Optional[WireSegmentPath],
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add connections to the specified port of this instance.

This method can establish multiple connections if a range of indices is provided.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection(s) should be established.

  • ws_path

    (Optional[WireSegmentPath]) –

    The path of the wire segment that will be connected to this port. If None, the associated port (segment) remains unconnected.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

Raises:

  • ObjectLockedError

    If this instance is currently locked, and no connection can be made.

disconnect

disconnect(port_name: str, index: Optional[int] = None) -> None

Remove an existing connection from a specified port of this instance.

This method disconnects the wire segment at the given index within the specified port_name.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be removed.

  • index

    (Optional[int], default: None ) –

    The bit index within the port for this disconnection. Defaults to None, which completely disconnects the port.

Raises:

get_connection

get_connection(
    port_name: str, index: Optional[NonNegativeInt] = None
) -> Union[WireSegmentPath, Dict[int, WireSegmentPath], None]

Retrieve the connection path associated with a specified port and bit index.

If index is provided, this method returns the wire segment path connected to that specific bit within the port. Otherwise, it returns all connections for the given port as a dictionary mapping indices to WireSegmentPaths.

Parameters:

  • port_name

    (str) –

    The name of the port for which to retrieve the connection(s).

  • index

    (Optional[NonNegativeInt], default: None ) –

    The bit index within the port. Defaults to None.

Returns:

modify_connection

modify_connection(
    port_name: str, ws_path: WireSegmentPath, index: NonNegativeInt = 0
) -> None

Modify an existing connection within a specified port of this instance.

This method updates the wire segment path at the given index within the specified port_name. If the index does not exist yet, it is newly added, changing the width of the port.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be modified.

  • ws_path

    (WireSegmentPath) –

    The new wire segment path for this connection.

  • index

    (NonNegativeInt, default: 0 ) –

    The bit index within the port. Defaults to 0.

connect_modify

connect_modify(
    port_name: str,
    ws_path: WireSegmentPath,
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add a new connection or modify an existing one within the specified port of this instance.

If the connection already exists at the given index and port_name, it will be modified. Otherwise, a new connection is added.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be established or updated.

  • ws_path

    (WireSegmentPath) –

    The path of the wire segment that will be connected to this port.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

tie_port

tie_port(name: str, index: NonNegativeInt, sig_value: LogicLevel) -> None

Set a constant signal value for the specified port and bit index.

If the specified port does not exist, an error message is logged and the function returns False. Otherwise, the method tries to set the constant signal value for that port and returns True if successful.

Does not work for instance output ports, as they are always driven by their parent instances.

Parameters:

  • name

    (str) –

    The name of the port.

  • index

    (NonNegativeInt) –

    The bit index within the port.

  • sig_value

    (LogicLevel) –

    The constant signal value to be set ('0', '1', or 'Z').

Raises:

  • ObjectNotFoundError

    If no such port or port segment exists.

  • AlreadyConnectedError

    (raised by: PortSegment.tie_signal) If this segment is belongs to a load port and is already connected to a wire, from which it receives its value.

  • InvalidDirectionError

    (raised by: PortSegment.tie_signal) If this port segment belongs to an instance output port, which is driven by the instance inputs and the instance's internal logic.

  • InvalidSignalError

    (raised by: PortSegment.tie_signal) If an invalid value is provided.

has_tied_ports

has_tied_ports() -> bool

Checks the ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any ports of this instance are tied to constant values. False otherwise, i.e. all ports are connected to wires.

has_tied_inputs

has_tied_inputs() -> bool

Checks the input ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any input ports of this instance are tied to constant values. False otherwise, i.e. all input ports are connected to wires.

has_tied_outputs

has_tied_outputs() -> bool

Checks the output ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any output ports of this instance are tied to constant values. False otherwise, i.e. all output ports are connected to wires.

update_signedness

update_signedness(port_name: str) -> None

Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

Parameters:

  • port_name

    (str) –

    The name of the port, of which the signedness value is retrieved.

split

split() -> Dict[NonNegativeInt, Self]

Performs a bit-wise split on this instance.

If this instance supports splitting and has a data width of n bit, this method splits this instance into n 1-bit instances. This works for instances, where each output bit depends only on the corresponding input bit(s), e.g. an AND gate or a D-Flipflop.

Returns:

  • Dict[NonNegativeInt, Self]

    Dict[int, Instance]: An n-bit large dictionary, where each key conforms to a bit of the original instance, and each value is an 1-bit instance representing the corresponding "slice" of the original instance.

Raises:

  • SplittingUnsupportedError

    If this instance does not support splitting. Happens for any gate or instance whose behavior depends on the whole bus, and splitting would make it lose its meaning.

p2v

p2v(
    port: ANY_PORT,
    exclude_indices: Optional[List[int]] = None,
    include_indices: Optional[List[int]] = None,
) -> str

Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a Port object and converts them to their corresponding Verilog signal structure (p2v -> Port to Verilog signal syntax). For each segment of the port, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port is set to a constant, the corresponding constant wire segment placeholder is used instead. Port segments can be excluded from the conversion by providing a list of indices to the exclude_indices parameter, indicating which segments should be excluded from the conversion (e.g. segments that are known to be unconnected). Vice versa, only a certain subset of the port's segments may be converted to Verilog syntax, if include_indices is a given list of port indices. All indices not present in the list will be excluded from the conversion.

Parameters:

  • port

    (Port) –

    The Port object to convert.

  • exclude_indices

    (List[int], default: None ) –

    A list of indices to exclude from the conversion. Defaults to None.

  • include_indices

    (List[int], default: None ) –

    A list of indices (i.e. port slices) to include only for the conversion. Defaults to None.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

  • ObjectNotFoundError

    If the wire connected to a certain port segment could not be found.

  • UnsupportedOperationError

    If both exclude_indices and include_indices are specified. Only one of both may be given when calling this method.

ps2v

Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a PortSegment dictionary and converts them to their corresponding Verilog signal structure (ps2v -> PortSegment to Verilog signal syntax). For each segment, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port segment is set to a constant, the corresponding constant wire segment placeholder is used instead.

Parameters:

  • ps_dict

    (Dict[int, PortSegment]) –

    The PortSegment dictionary to convert. Each key (int) conforms to the index of the associated PortSegment object.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

set

set(
    port_name: str,
    new_signal: SignalOrLogicLevel,
    idx: Union[int, List[int]] = 0,
) -> None

Sets the signal on a port.

Parameters:

  • port_name

    (str) –

    The name of the port to set the signal on.

  • new_signal

    (Signal) –

    The new signal value.

  • idx

    (Union[int, List[int]], default: 0 ) –

    The index (or indices) to apply the given signal to. Can either be an integer (single index to set) or an iterable of integers (e.g. a list of indices). For every integer of the iterable the signal value of the corresponding port index is set to the given new_signal. Defaults to 0.

Example

from netlist_carpentry.utils.gate_factory import and_gate module = Module(name='m') a = module.create_port('a', 'input', width=6) instance = and_gate(module, 'inst', A=a)

This sets the value of bit 0 of port A to HIGH

instance.set('A', 1, 0) instance.ports['A'].signal_str 'xxxxx1'

This sets the value of bits 1, 3 and 5 of port A to LOW, leaving the other bits as they already are.

instance.set('A', 0, [1, 3, 5]) instance.ports['A'].signal_str '0x0x01'

get_result

get_result(s1: Signal, s2: Signal) -> Signal

Returns the result of this gate's operation for given Signals s1 and s2.

This method is only implemented for bitwise evaluating gates (e.g. AndGate, OrGate). This method raises an UnsupportedOperationError if used on other gates (e.g. Adder).

For vector-level operations on full signal arrays, use :meth:get_result_vector instead.

Parameters:

  • s1

    (Signal) –

    The first Signal, i.e. the first operand.

  • s2

    (Signal) –

    The second Signal, i.e. the second operand.

Raises:

Returns:

  • Signal ( Signal ) –

    The result of this gate's operation on the given signals.

signals_in

signals_in(idx: NonNegativeInt = 0) -> Tuple[Signal, Signal]

The input signals of the gate.

Returns:

signal_out

signal_out(idx: NonNegativeInt = 0) -> Signal

The output signal of the gate.

Returns:

  • Signal ( Signal ) –

    The output signal of the gate.

DFF

Bases: ClkMixin, StorageGate, BaseModel

A D flip-flop (DFF) is a clocked gate that stores a value on its input port and outputs it on its output port. The value is stored when the clock signal has a rising edge. The most basic version only has 3 ports: D, Q and CLK. en_polarity (Signal): The polarity of the enable signal.

Methods:

  • get_scanff

    Creates and returns a scan-DFF version of this DFF, copying all parameters of this DFF.

  • evaluate

    Evaluates the gate's output signal.

  • change_mutability

    Change the mutability status of this instance and optionally its ports.

  • all_connections

    Returns a dictionary mapping port names to their corresponding connection paths.

  • model_post_init

    Initializes the gate's ports and connections.

  • connect

    Add connections to the specified port of this instance.

  • disconnect

    Remove an existing connection from a specified port of this instance.

  • get_connection

    Retrieve the connection path associated with a specified port and bit index.

  • modify_connection

    Modify an existing connection within a specified port of this instance.

  • connect_modify

    Add a new connection or modify an existing one within the specified port of this instance.

  • tie_port

    Set a constant signal value for the specified port and bit index.

  • has_tied_ports

    Checks the ports of this instance whether any are tied to constant values.

  • has_tied_inputs

    Checks the input ports of this instance whether any are tied to constant values.

  • has_tied_outputs

    Checks the output ports of this instance whether any are tied to constant values.

  • update_signedness

    Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

  • split

    Performs a bit-wise split on this instance.

  • p2v

    Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

  • ps2v

    Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

  • set

    Sets the signal on a port.

  • set_clk

    Sets the clock signal.

Attributes:

instance_type class-attribute instance-attribute

instance_type: str = f'{CFG.id_internal}dff'

Instance type descriptor for D-Flip-Flops. Defaults to §dff, but may be overwritten upon creation by Yosys.

Yosys introduces a variety of flip-flop descriptor types. See the Yosys documentation for more information.

has_en property

has_en: bool

Whether this DFF instance has an EN (enable) port.

has_rst property

has_rst: bool

Whether this DFF instance has an RST (reset) port.

scan_ff_equivalent property

scan_ff_equivalent: Type[ScanDFF]

Returns the Scan-FF type equivalent for normal FF and the FF type equivalent for Scan-FF.

name instance-attribute

name: str

The name of the element.

!!! Do not modify this variable after instantiating it. Use NetlistElement.set_name() instead. Modifying this variable might lead to inconsistencies later on.

metadata class-attribute instance-attribute

Metadata of a netlist element.

Can be user-defined, or e. g. by Yosys (such as src for the HDL source). Is also grouped by categories, i.e. all metadata from Yosys can be accessed via Module.metadata["yosys"], or via Module.metadata.yosys, which both return a dictionary of all metadata. Read the documentation of MetaDataMixin for more information.

path property

Returns the InstancePath of the netlist element.

The InstancePath object is constructed using the element's type and its raw hierarchical path.

Returns:

  • InstancePath ( InstancePath ) –

    The hierarchical path of the netlist element.

type property

type: EType

The type of the element, which is an instance.

hierarchy_level property

hierarchy_level: int

The level of hierarchy of the element in the design.

The hierarchy level is the number of separators in the element's raw path. For example, a top-level instance has a hierarchy level of 0, while a direct submodule instance has a hierarchy level of 1.

Returns:

  • int ( int ) –

    The hierarchy level of the element.

has_parent property

has_parent: bool

Whether this object has a parent.

circuit property

circuit: 'Circuit'

The circuit object to which this netlist element belongs to.

  • For a module, returns the circuit to which the module belongs.
  • For any other netlist element, recursively returns the circuit of the parent, which ultimately leads to a module, to which the netlist element belongs.

Raises:

  • ParentNotFoundError

    If a parent cannot be resolved somewhere in the hierarchical chain.

  • ObjectNotFoundError

    If for a module no circuit is set.

has_circuit property

has_circuit: bool

Whether this netlist element has a defined circuit it belongs to.

Tries to access self.circuit and returns whether the call was successful. Can be used instead of a try-except clause around the call to NetlistElement.circuit.

locked property

locked: bool

True if this NetlistElement instance is locked (i.e. it is currently structurally unchangeable), False if it is mutable.

Can be changed via NetlistElement.change_mutability(bool).

Immutability is used to prevent accidental changes to the design.

is_placeholder_instance property

is_placeholder_instance: bool

A placeholder represents an element that does not have a specific path.

True if this NetlistElement instance represents a placeholder, False otherwise.

can_carry_signal property

can_carry_signal: bool

Whether this exact object is able to receive, pass or hold signal values.

True for ports (as they drive or receive values) and wires (as they pass the signals from driver to load ports) as well as their respective segments. False for instances and modules.

connections property

connections: Dict[str, Dict[int, WireSegmentPath]]

A dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port. Elements with no connection (i.e. the path is None) are excluded. In case these are needed, use Instance.get_connections() instead.

Example

{ 'port1': {1: WireSegmentPath('path/to/element1'), 2: WireSegmentPath('path/to/element2')}, 'port2': {1: WireSegmentPath('path/to/element3')} }

connection_str_paths property

connection_str_paths: Dict[str, Dict[int, str]]

Returns a dictionary mapping port names to their corresponding connection paths as strings.

The keys are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are the raw string paths.

Example

{ 'port1': {0: 'path.to.element1', 1: 'path.to.element2'}, 'port2': {0: 'path.to.element3'} }

ports property

A dictionary mapping port names to their corresponding Port objects.

The keys of the dictionary are the names of the ports. The values are Port objects representing the ports.

Returns:

input_ports property

input_ports: Tuple[Port[Instance], ...]

Returns a tuple of input ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as inputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the input ports.

output_ports property

output_ports: Tuple[Port[Instance], ...]

Returns a tuple of output ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as outputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the output ports.

has_unconnected_port_segments property

has_unconnected_port_segments: bool

Returns True if the instance has at least one unconnected port segment.

signals property

signals: Dict[str, SignalArray]

A dictionary with all signals currently present on all ports of this instance.

is_blackbox property

is_blackbox: bool

Flag indicating whether the instance represents neither a primitive element nor a module instance.

If True, this instance does not have a module definition, and is also not a basic component (i.e. a primitive gate instance) from the internal gate library, such as a gate or flip-flop.

a_width property

a_width: PositiveInt

Width of the gate's A port.

b_width property

b_width: PositiveInt

Width of the gate's B port.

is_sequential property

is_sequential: bool

Whether instances of this gate are considered sequential gates.

False for combinational gates, such as AND gates or arithmetic gates. True for flip-flops and latches.

output_port property

output_port: Port[Instance]

The output port of the gate.

data_width property

data_width: int

The data width of this instance.

Defaults to the data width of the output port. Can be overwritten in extended classes.

In contrast to self.width, which is used for the creation and initialization, this property is linked to the data width of the output port. This property is useful when the data width of the output port can be changed.

input_port property

input_port: Port[Instance]

The input port of the gate.

clk_polarity property writable

clk_polarity: Signal

Which clock edge activates the flip-flop. Default is Signal.HIGH, i.e. rising edge.

clk_port property

clk_port: Port[Instance]

The clock port of the gate.

get_scanff

get_scanff() -> ScanDFF

Creates and returns a scan-DFF version of this DFF, copying all parameters of this DFF.

No connections are copied however, and the instance initially does not belong to any module.

evaluate

evaluate() -> None

Evaluates the gate's output signal.

This method is called when the gate's input signals change, and it updates the gate's output signal accordingly.

change_mutability

change_mutability(is_now_locked: bool, recursive: bool = False) -> Self

Change the mutability status of this instance and optionally its ports.

This method allows setting whether this instance can be modified or not. If recursive is set to True, it also applies the same mutability status to all ports of this instance.

Parameters:

  • is_now_locked

    (bool) –

    The new mutability status for this instance.

  • recursive

    (bool, default: False ) –

    Whether to apply the change recursively to its ports. Defaults to False.

all_connections

all_connections(
    include_unconnected: bool,
) -> Dict[str, Dict[int, WireSegmentPath]]

Returns a dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port.

Parameters:

  • include_unconnected

    (bool) –

    Whether to include unconnected ports in the result.

Returns:

model_post_init

model_post_init(__context: object) -> None

Initializes the gate's ports and connections.

This method is called after the gate's attributes have been initialized, and it sets up the gate's ports and connections.

connect

connect(
    port_name: str,
    ws_path: Optional[WireSegmentPath],
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add connections to the specified port of this instance.

This method can establish multiple connections if a range of indices is provided.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection(s) should be established.

  • ws_path

    (Optional[WireSegmentPath]) –

    The path of the wire segment that will be connected to this port. If None, the associated port (segment) remains unconnected.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

Raises:

  • ObjectLockedError

    If this instance is currently locked, and no connection can be made.

disconnect

disconnect(port_name: str, index: Optional[int] = None) -> None

Remove an existing connection from a specified port of this instance.

This method disconnects the wire segment at the given index within the specified port_name.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be removed.

  • index

    (Optional[int], default: None ) –

    The bit index within the port for this disconnection. Defaults to None, which completely disconnects the port.

Raises:

get_connection

get_connection(
    port_name: str, index: Optional[NonNegativeInt] = None
) -> Union[WireSegmentPath, Dict[int, WireSegmentPath], None]

Retrieve the connection path associated with a specified port and bit index.

If index is provided, this method returns the wire segment path connected to that specific bit within the port. Otherwise, it returns all connections for the given port as a dictionary mapping indices to WireSegmentPaths.

Parameters:

  • port_name

    (str) –

    The name of the port for which to retrieve the connection(s).

  • index

    (Optional[NonNegativeInt], default: None ) –

    The bit index within the port. Defaults to None.

Returns:

modify_connection

modify_connection(
    port_name: str, ws_path: WireSegmentPath, index: NonNegativeInt = 0
) -> None

Modify an existing connection within a specified port of this instance.

This method updates the wire segment path at the given index within the specified port_name. If the index does not exist yet, it is newly added, changing the width of the port.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be modified.

  • ws_path

    (WireSegmentPath) –

    The new wire segment path for this connection.

  • index

    (NonNegativeInt, default: 0 ) –

    The bit index within the port. Defaults to 0.

connect_modify

connect_modify(
    port_name: str,
    ws_path: WireSegmentPath,
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add a new connection or modify an existing one within the specified port of this instance.

If the connection already exists at the given index and port_name, it will be modified. Otherwise, a new connection is added.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be established or updated.

  • ws_path

    (WireSegmentPath) –

    The path of the wire segment that will be connected to this port.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

tie_port

tie_port(name: str, index: NonNegativeInt, sig_value: LogicLevel) -> None

Set a constant signal value for the specified port and bit index.

If the specified port does not exist, an error message is logged and the function returns False. Otherwise, the method tries to set the constant signal value for that port and returns True if successful.

Does not work for instance output ports, as they are always driven by their parent instances.

Parameters:

  • name

    (str) –

    The name of the port.

  • index

    (NonNegativeInt) –

    The bit index within the port.

  • sig_value

    (LogicLevel) –

    The constant signal value to be set ('0', '1', or 'Z').

Raises:

  • ObjectNotFoundError

    If no such port or port segment exists.

  • AlreadyConnectedError

    (raised by: PortSegment.tie_signal) If this segment is belongs to a load port and is already connected to a wire, from which it receives its value.

  • InvalidDirectionError

    (raised by: PortSegment.tie_signal) If this port segment belongs to an instance output port, which is driven by the instance inputs and the instance's internal logic.

  • InvalidSignalError

    (raised by: PortSegment.tie_signal) If an invalid value is provided.

has_tied_ports

has_tied_ports() -> bool

Checks the ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any ports of this instance are tied to constant values. False otherwise, i.e. all ports are connected to wires.

has_tied_inputs

has_tied_inputs() -> bool

Checks the input ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any input ports of this instance are tied to constant values. False otherwise, i.e. all input ports are connected to wires.

has_tied_outputs

has_tied_outputs() -> bool

Checks the output ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any output ports of this instance are tied to constant values. False otherwise, i.e. all output ports are connected to wires.

update_signedness

update_signedness(port_name: str) -> None

Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

Parameters:

  • port_name

    (str) –

    The name of the port, of which the signedness value is retrieved.

split

split() -> Dict[NonNegativeInt, Self]

Performs a bit-wise split on this instance.

If this instance supports splitting and has a data width of n bit, this method splits this instance into n 1-bit instances. This works for instances, where each output bit depends only on the corresponding input bit(s), e.g. an AND gate or a D-Flipflop.

Returns:

  • Dict[NonNegativeInt, Self]

    Dict[int, Instance]: An n-bit large dictionary, where each key conforms to a bit of the original instance, and each value is an 1-bit instance representing the corresponding "slice" of the original instance.

Raises:

  • SplittingUnsupportedError

    If this instance does not support splitting. Happens for any gate or instance whose behavior depends on the whole bus, and splitting would make it lose its meaning.

p2v

p2v(
    port: ANY_PORT,
    exclude_indices: Optional[List[int]] = None,
    include_indices: Optional[List[int]] = None,
) -> str

Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a Port object and converts them to their corresponding Verilog signal structure (p2v -> Port to Verilog signal syntax). For each segment of the port, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port is set to a constant, the corresponding constant wire segment placeholder is used instead. Port segments can be excluded from the conversion by providing a list of indices to the exclude_indices parameter, indicating which segments should be excluded from the conversion (e.g. segments that are known to be unconnected). Vice versa, only a certain subset of the port's segments may be converted to Verilog syntax, if include_indices is a given list of port indices. All indices not present in the list will be excluded from the conversion.

Parameters:

  • port

    (Port) –

    The Port object to convert.

  • exclude_indices

    (List[int], default: None ) –

    A list of indices to exclude from the conversion. Defaults to None.

  • include_indices

    (List[int], default: None ) –

    A list of indices (i.e. port slices) to include only for the conversion. Defaults to None.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

  • ObjectNotFoundError

    If the wire connected to a certain port segment could not be found.

  • UnsupportedOperationError

    If both exclude_indices and include_indices are specified. Only one of both may be given when calling this method.

ps2v

Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a PortSegment dictionary and converts them to their corresponding Verilog signal structure (ps2v -> PortSegment to Verilog signal syntax). For each segment, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port segment is set to a constant, the corresponding constant wire segment placeholder is used instead.

Parameters:

  • ps_dict

    (Dict[int, PortSegment]) –

    The PortSegment dictionary to convert. Each key (int) conforms to the index of the associated PortSegment object.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

set

set(
    port_name: str,
    new_signal: SignalOrLogicLevel,
    idx: Union[int, List[int]] = 0,
) -> None

Sets the signal on a port.

Parameters:

  • port_name

    (str) –

    The name of the port to set the signal on.

  • new_signal

    (Signal) –

    The new signal value.

  • idx

    (Union[int, List[int]], default: 0 ) –

    The index (or indices) to apply the given signal to. Can either be an integer (single index to set) or an iterable of integers (e.g. a list of indices). For every integer of the iterable the signal value of the corresponding port index is set to the given new_signal. Defaults to 0.

Example

from netlist_carpentry.utils.gate_factory import and_gate module = Module(name='m') a = module.create_port('a', 'input', width=6) instance = and_gate(module, 'inst', A=a)

This sets the value of bit 0 of port A to HIGH

instance.set('A', 1, 0) instance.ports['A'].signal_str 'xxxxx1'

This sets the value of bits 1, 3 and 5 of port A to LOW, leaving the other bits as they already are.

instance.set('A', 0, [1, 3, 5]) instance.ports['A'].signal_str '0x0x01'

set_clk

set_clk(new_signal: SignalOrLogicLevel) -> None

Sets the clock signal.

Parameters:

  • new_signal

    (Signal) –

    The new clock signal value.

ADFF

Bases: RstMixin, DFF

Asynchronously resettable DFF.

Methods:

  • change_mutability

    Change the mutability status of this instance and optionally its ports.

  • evaluate

    Evaluates the gate's output signal.

  • all_connections

    Returns a dictionary mapping port names to their corresponding connection paths.

  • connect

    Add connections to the specified port of this instance.

  • disconnect

    Remove an existing connection from a specified port of this instance.

  • get_connection

    Retrieve the connection path associated with a specified port and bit index.

  • modify_connection

    Modify an existing connection within a specified port of this instance.

  • connect_modify

    Add a new connection or modify an existing one within the specified port of this instance.

  • tie_port

    Set a constant signal value for the specified port and bit index.

  • has_tied_ports

    Checks the ports of this instance whether any are tied to constant values.

  • has_tied_inputs

    Checks the input ports of this instance whether any are tied to constant values.

  • has_tied_outputs

    Checks the output ports of this instance whether any are tied to constant values.

  • update_signedness

    Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

  • split

    Performs a bit-wise split on this instance.

  • p2v

    Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

  • ps2v

    Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

  • set

    Sets the signal on a port.

  • set_clk

    Sets the clock signal.

  • get_scanff

    Creates and returns a scan-DFF version of this DFF, copying all parameters of this DFF.

  • set_rst

    Sets the reset signal.

Attributes:

name instance-attribute

name: str

The name of the element.

!!! Do not modify this variable after instantiating it. Use NetlistElement.set_name() instead. Modifying this variable might lead to inconsistencies later on.

metadata class-attribute instance-attribute

Metadata of a netlist element.

Can be user-defined, or e. g. by Yosys (such as src for the HDL source). Is also grouped by categories, i.e. all metadata from Yosys can be accessed via Module.metadata["yosys"], or via Module.metadata.yosys, which both return a dictionary of all metadata. Read the documentation of MetaDataMixin for more information.

path property

Returns the InstancePath of the netlist element.

The InstancePath object is constructed using the element's type and its raw hierarchical path.

Returns:

  • InstancePath ( InstancePath ) –

    The hierarchical path of the netlist element.

type property

type: EType

The type of the element, which is an instance.

hierarchy_level property

hierarchy_level: int

The level of hierarchy of the element in the design.

The hierarchy level is the number of separators in the element's raw path. For example, a top-level instance has a hierarchy level of 0, while a direct submodule instance has a hierarchy level of 1.

Returns:

  • int ( int ) –

    The hierarchy level of the element.

has_parent property

has_parent: bool

Whether this object has a parent.

circuit property

circuit: 'Circuit'

The circuit object to which this netlist element belongs to.

  • For a module, returns the circuit to which the module belongs.
  • For any other netlist element, recursively returns the circuit of the parent, which ultimately leads to a module, to which the netlist element belongs.

Raises:

  • ParentNotFoundError

    If a parent cannot be resolved somewhere in the hierarchical chain.

  • ObjectNotFoundError

    If for a module no circuit is set.

has_circuit property

has_circuit: bool

Whether this netlist element has a defined circuit it belongs to.

Tries to access self.circuit and returns whether the call was successful. Can be used instead of a try-except clause around the call to NetlistElement.circuit.

locked property

locked: bool

True if this NetlistElement instance is locked (i.e. it is currently structurally unchangeable), False if it is mutable.

Can be changed via NetlistElement.change_mutability(bool).

Immutability is used to prevent accidental changes to the design.

is_placeholder_instance property

is_placeholder_instance: bool

A placeholder represents an element that does not have a specific path.

True if this NetlistElement instance represents a placeholder, False otherwise.

can_carry_signal property

can_carry_signal: bool

Whether this exact object is able to receive, pass or hold signal values.

True for ports (as they drive or receive values) and wires (as they pass the signals from driver to load ports) as well as their respective segments. False for instances and modules.

connections property

connections: Dict[str, Dict[int, WireSegmentPath]]

A dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port. Elements with no connection (i.e. the path is None) are excluded. In case these are needed, use Instance.get_connections() instead.

Example

{ 'port1': {1: WireSegmentPath('path/to/element1'), 2: WireSegmentPath('path/to/element2')}, 'port2': {1: WireSegmentPath('path/to/element3')} }

connection_str_paths property

connection_str_paths: Dict[str, Dict[int, str]]

Returns a dictionary mapping port names to their corresponding connection paths as strings.

The keys are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are the raw string paths.

Example

{ 'port1': {0: 'path.to.element1', 1: 'path.to.element2'}, 'port2': {0: 'path.to.element3'} }

ports property

A dictionary mapping port names to their corresponding Port objects.

The keys of the dictionary are the names of the ports. The values are Port objects representing the ports.

Returns:

input_ports property

input_ports: Tuple[Port[Instance], ...]

Returns a tuple of input ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as inputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the input ports.

output_ports property

output_ports: Tuple[Port[Instance], ...]

Returns a tuple of output ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as outputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the output ports.

has_unconnected_port_segments property

has_unconnected_port_segments: bool

Returns True if the instance has at least one unconnected port segment.

signals property

signals: Dict[str, SignalArray]

A dictionary with all signals currently present on all ports of this instance.

is_blackbox property

is_blackbox: bool

Flag indicating whether the instance represents neither a primitive element nor a module instance.

If True, this instance does not have a module definition, and is also not a basic component (i.e. a primitive gate instance) from the internal gate library, such as a gate or flip-flop.

a_width property

a_width: PositiveInt

Width of the gate's A port.

b_width property

b_width: PositiveInt

Width of the gate's B port.

is_sequential property

is_sequential: bool

Whether instances of this gate are considered sequential gates.

False for combinational gates, such as AND gates or arithmetic gates. True for flip-flops and latches.

output_port property

output_port: Port[Instance]

The output port of the gate.

data_width property

data_width: int

The data width of this instance.

Defaults to the data width of the output port. Can be overwritten in extended classes.

In contrast to self.width, which is used for the creation and initialization, this property is linked to the data width of the output port. This property is useful when the data width of the output port can be changed.

input_port property

input_port: Port[Instance]

The input port of the gate.

clk_polarity property writable

clk_polarity: Signal

Which clock edge activates the flip-flop. Default is Signal.HIGH, i.e. rising edge.

clk_port property

clk_port: Port[Instance]

The clock port of the gate.

has_en property

has_en: bool

Whether this DFF instance has an EN (enable) port.

has_rst property

has_rst: bool

Whether this DFF instance has an RST (reset) port.

scan_ff_equivalent property

scan_ff_equivalent: Type[ScanDFF]

Returns the Scan-FF type equivalent for normal FF and the FF type equivalent for Scan-FF.

rst_polarity property writable

rst_polarity: Signal

Which reset level resets the flip-flop. Default is Signal.HIGH: the flipflop is in reset, if the reset signal is HIGH.

rst_val_int property writable

rst_val_int: int

Reset value of the flip-flop as integer. Default is 0.

rst_port property

rst_port: Port[Instance]

The reset port of the gate.

rst_val property

rst_val: SignalArray

The value of the flipflop during and after reset. Default is Signal.LOW, i.e. the initial flipflop state is 0 by default.

in_reset property

in_reset: bool

True if the gate is currently in reset, False otherwise.

change_mutability

change_mutability(is_now_locked: bool, recursive: bool = False) -> Self

Change the mutability status of this instance and optionally its ports.

This method allows setting whether this instance can be modified or not. If recursive is set to True, it also applies the same mutability status to all ports of this instance.

Parameters:

  • is_now_locked

    (bool) –

    The new mutability status for this instance.

  • recursive

    (bool, default: False ) –

    Whether to apply the change recursively to its ports. Defaults to False.

evaluate

evaluate() -> None

Evaluates the gate's output signal.

This method is called when the gate's input signals change, and it updates the gate's output signal accordingly.

all_connections

all_connections(
    include_unconnected: bool,
) -> Dict[str, Dict[int, WireSegmentPath]]

Returns a dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port.

Parameters:

  • include_unconnected

    (bool) –

    Whether to include unconnected ports in the result.

Returns:

connect

connect(
    port_name: str,
    ws_path: Optional[WireSegmentPath],
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add connections to the specified port of this instance.

This method can establish multiple connections if a range of indices is provided.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection(s) should be established.

  • ws_path

    (Optional[WireSegmentPath]) –

    The path of the wire segment that will be connected to this port. If None, the associated port (segment) remains unconnected.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

Raises:

  • ObjectLockedError

    If this instance is currently locked, and no connection can be made.

disconnect

disconnect(port_name: str, index: Optional[int] = None) -> None

Remove an existing connection from a specified port of this instance.

This method disconnects the wire segment at the given index within the specified port_name.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be removed.

  • index

    (Optional[int], default: None ) –

    The bit index within the port for this disconnection. Defaults to None, which completely disconnects the port.

Raises:

get_connection

get_connection(
    port_name: str, index: Optional[NonNegativeInt] = None
) -> Union[WireSegmentPath, Dict[int, WireSegmentPath], None]

Retrieve the connection path associated with a specified port and bit index.

If index is provided, this method returns the wire segment path connected to that specific bit within the port. Otherwise, it returns all connections for the given port as a dictionary mapping indices to WireSegmentPaths.

Parameters:

  • port_name

    (str) –

    The name of the port for which to retrieve the connection(s).

  • index

    (Optional[NonNegativeInt], default: None ) –

    The bit index within the port. Defaults to None.

Returns:

modify_connection

modify_connection(
    port_name: str, ws_path: WireSegmentPath, index: NonNegativeInt = 0
) -> None

Modify an existing connection within a specified port of this instance.

This method updates the wire segment path at the given index within the specified port_name. If the index does not exist yet, it is newly added, changing the width of the port.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be modified.

  • ws_path

    (WireSegmentPath) –

    The new wire segment path for this connection.

  • index

    (NonNegativeInt, default: 0 ) –

    The bit index within the port. Defaults to 0.

connect_modify

connect_modify(
    port_name: str,
    ws_path: WireSegmentPath,
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add a new connection or modify an existing one within the specified port of this instance.

If the connection already exists at the given index and port_name, it will be modified. Otherwise, a new connection is added.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be established or updated.

  • ws_path

    (WireSegmentPath) –

    The path of the wire segment that will be connected to this port.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

tie_port

tie_port(name: str, index: NonNegativeInt, sig_value: LogicLevel) -> None

Set a constant signal value for the specified port and bit index.

If the specified port does not exist, an error message is logged and the function returns False. Otherwise, the method tries to set the constant signal value for that port and returns True if successful.

Does not work for instance output ports, as they are always driven by their parent instances.

Parameters:

  • name

    (str) –

    The name of the port.

  • index

    (NonNegativeInt) –

    The bit index within the port.

  • sig_value

    (LogicLevel) –

    The constant signal value to be set ('0', '1', or 'Z').

Raises:

  • ObjectNotFoundError

    If no such port or port segment exists.

  • AlreadyConnectedError

    (raised by: PortSegment.tie_signal) If this segment is belongs to a load port and is already connected to a wire, from which it receives its value.

  • InvalidDirectionError

    (raised by: PortSegment.tie_signal) If this port segment belongs to an instance output port, which is driven by the instance inputs and the instance's internal logic.

  • InvalidSignalError

    (raised by: PortSegment.tie_signal) If an invalid value is provided.

has_tied_ports

has_tied_ports() -> bool

Checks the ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any ports of this instance are tied to constant values. False otherwise, i.e. all ports are connected to wires.

has_tied_inputs

has_tied_inputs() -> bool

Checks the input ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any input ports of this instance are tied to constant values. False otherwise, i.e. all input ports are connected to wires.

has_tied_outputs

has_tied_outputs() -> bool

Checks the output ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any output ports of this instance are tied to constant values. False otherwise, i.e. all output ports are connected to wires.

update_signedness

update_signedness(port_name: str) -> None

Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

Parameters:

  • port_name

    (str) –

    The name of the port, of which the signedness value is retrieved.

split

split() -> Dict[NonNegativeInt, Self]

Performs a bit-wise split on this instance.

If this instance supports splitting and has a data width of n bit, this method splits this instance into n 1-bit instances. This works for instances, where each output bit depends only on the corresponding input bit(s), e.g. an AND gate or a D-Flipflop.

Returns:

  • Dict[NonNegativeInt, Self]

    Dict[int, Instance]: An n-bit large dictionary, where each key conforms to a bit of the original instance, and each value is an 1-bit instance representing the corresponding "slice" of the original instance.

Raises:

  • SplittingUnsupportedError

    If this instance does not support splitting. Happens for any gate or instance whose behavior depends on the whole bus, and splitting would make it lose its meaning.

p2v

p2v(
    port: ANY_PORT,
    exclude_indices: Optional[List[int]] = None,
    include_indices: Optional[List[int]] = None,
) -> str

Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a Port object and converts them to their corresponding Verilog signal structure (p2v -> Port to Verilog signal syntax). For each segment of the port, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port is set to a constant, the corresponding constant wire segment placeholder is used instead. Port segments can be excluded from the conversion by providing a list of indices to the exclude_indices parameter, indicating which segments should be excluded from the conversion (e.g. segments that are known to be unconnected). Vice versa, only a certain subset of the port's segments may be converted to Verilog syntax, if include_indices is a given list of port indices. All indices not present in the list will be excluded from the conversion.

Parameters:

  • port

    (Port) –

    The Port object to convert.

  • exclude_indices

    (List[int], default: None ) –

    A list of indices to exclude from the conversion. Defaults to None.

  • include_indices

    (List[int], default: None ) –

    A list of indices (i.e. port slices) to include only for the conversion. Defaults to None.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

  • ObjectNotFoundError

    If the wire connected to a certain port segment could not be found.

  • UnsupportedOperationError

    If both exclude_indices and include_indices are specified. Only one of both may be given when calling this method.

ps2v

Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a PortSegment dictionary and converts them to their corresponding Verilog signal structure (ps2v -> PortSegment to Verilog signal syntax). For each segment, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port segment is set to a constant, the corresponding constant wire segment placeholder is used instead.

Parameters:

  • ps_dict

    (Dict[int, PortSegment]) –

    The PortSegment dictionary to convert. Each key (int) conforms to the index of the associated PortSegment object.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

set

set(
    port_name: str,
    new_signal: SignalOrLogicLevel,
    idx: Union[int, List[int]] = 0,
) -> None

Sets the signal on a port.

Parameters:

  • port_name

    (str) –

    The name of the port to set the signal on.

  • new_signal

    (Signal) –

    The new signal value.

  • idx

    (Union[int, List[int]], default: 0 ) –

    The index (or indices) to apply the given signal to. Can either be an integer (single index to set) or an iterable of integers (e.g. a list of indices). For every integer of the iterable the signal value of the corresponding port index is set to the given new_signal. Defaults to 0.

Example

from netlist_carpentry.utils.gate_factory import and_gate module = Module(name='m') a = module.create_port('a', 'input', width=6) instance = and_gate(module, 'inst', A=a)

This sets the value of bit 0 of port A to HIGH

instance.set('A', 1, 0) instance.ports['A'].signal_str 'xxxxx1'

This sets the value of bits 1, 3 and 5 of port A to LOW, leaving the other bits as they already are.

instance.set('A', 0, [1, 3, 5]) instance.ports['A'].signal_str '0x0x01'

set_clk

set_clk(new_signal: SignalOrLogicLevel) -> None

Sets the clock signal.

Parameters:

  • new_signal

    (Signal) –

    The new clock signal value.

get_scanff

get_scanff() -> ScanDFF

Creates and returns a scan-DFF version of this DFF, copying all parameters of this DFF.

No connections are copied however, and the instance initially does not belong to any module.

set_rst

set_rst(new_signal: SignalOrLogicLevel) -> None

Sets the reset signal.

Parameters:

  • new_signal

    (Signal) –

    The new reset signal value.

DFFE

Bases: EnMixin, DFF

DFF with enable port.

Methods:

  • change_mutability

    Change the mutability status of this instance and optionally its ports.

  • evaluate

    Evaluates the gate's output signal.

  • all_connections

    Returns a dictionary mapping port names to their corresponding connection paths.

  • connect

    Add connections to the specified port of this instance.

  • disconnect

    Remove an existing connection from a specified port of this instance.

  • get_connection

    Retrieve the connection path associated with a specified port and bit index.

  • modify_connection

    Modify an existing connection within a specified port of this instance.

  • connect_modify

    Add a new connection or modify an existing one within the specified port of this instance.

  • tie_port

    Set a constant signal value for the specified port and bit index.

  • has_tied_ports

    Checks the ports of this instance whether any are tied to constant values.

  • has_tied_inputs

    Checks the input ports of this instance whether any are tied to constant values.

  • has_tied_outputs

    Checks the output ports of this instance whether any are tied to constant values.

  • update_signedness

    Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

  • split

    Performs a bit-wise split on this instance.

  • p2v

    Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

  • ps2v

    Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

  • set

    Sets the signal on a port.

  • set_clk

    Sets the clock signal.

  • get_scanff

    Creates and returns a scan-DFF version of this DFF, copying all parameters of this DFF.

  • set_en

    Sets the enable signal.

Attributes:

name instance-attribute

name: str

The name of the element.

!!! Do not modify this variable after instantiating it. Use NetlistElement.set_name() instead. Modifying this variable might lead to inconsistencies later on.

metadata class-attribute instance-attribute

Metadata of a netlist element.

Can be user-defined, or e. g. by Yosys (such as src for the HDL source). Is also grouped by categories, i.e. all metadata from Yosys can be accessed via Module.metadata["yosys"], or via Module.metadata.yosys, which both return a dictionary of all metadata. Read the documentation of MetaDataMixin for more information.

path property

Returns the InstancePath of the netlist element.

The InstancePath object is constructed using the element's type and its raw hierarchical path.

Returns:

  • InstancePath ( InstancePath ) –

    The hierarchical path of the netlist element.

type property

type: EType

The type of the element, which is an instance.

hierarchy_level property

hierarchy_level: int

The level of hierarchy of the element in the design.

The hierarchy level is the number of separators in the element's raw path. For example, a top-level instance has a hierarchy level of 0, while a direct submodule instance has a hierarchy level of 1.

Returns:

  • int ( int ) –

    The hierarchy level of the element.

has_parent property

has_parent: bool

Whether this object has a parent.

circuit property

circuit: 'Circuit'

The circuit object to which this netlist element belongs to.

  • For a module, returns the circuit to which the module belongs.
  • For any other netlist element, recursively returns the circuit of the parent, which ultimately leads to a module, to which the netlist element belongs.

Raises:

  • ParentNotFoundError

    If a parent cannot be resolved somewhere in the hierarchical chain.

  • ObjectNotFoundError

    If for a module no circuit is set.

has_circuit property

has_circuit: bool

Whether this netlist element has a defined circuit it belongs to.

Tries to access self.circuit and returns whether the call was successful. Can be used instead of a try-except clause around the call to NetlistElement.circuit.

locked property

locked: bool

True if this NetlistElement instance is locked (i.e. it is currently structurally unchangeable), False if it is mutable.

Can be changed via NetlistElement.change_mutability(bool).

Immutability is used to prevent accidental changes to the design.

is_placeholder_instance property

is_placeholder_instance: bool

A placeholder represents an element that does not have a specific path.

True if this NetlistElement instance represents a placeholder, False otherwise.

can_carry_signal property

can_carry_signal: bool

Whether this exact object is able to receive, pass or hold signal values.

True for ports (as they drive or receive values) and wires (as they pass the signals from driver to load ports) as well as their respective segments. False for instances and modules.

connections property

connections: Dict[str, Dict[int, WireSegmentPath]]

A dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port. Elements with no connection (i.e. the path is None) are excluded. In case these are needed, use Instance.get_connections() instead.

Example

{ 'port1': {1: WireSegmentPath('path/to/element1'), 2: WireSegmentPath('path/to/element2')}, 'port2': {1: WireSegmentPath('path/to/element3')} }

connection_str_paths property

connection_str_paths: Dict[str, Dict[int, str]]

Returns a dictionary mapping port names to their corresponding connection paths as strings.

The keys are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are the raw string paths.

Example

{ 'port1': {0: 'path.to.element1', 1: 'path.to.element2'}, 'port2': {0: 'path.to.element3'} }

ports property

A dictionary mapping port names to their corresponding Port objects.

The keys of the dictionary are the names of the ports. The values are Port objects representing the ports.

Returns:

input_ports property

input_ports: Tuple[Port[Instance], ...]

Returns a tuple of input ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as inputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the input ports.

output_ports property

output_ports: Tuple[Port[Instance], ...]

Returns a tuple of output ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as outputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the output ports.

has_unconnected_port_segments property

has_unconnected_port_segments: bool

Returns True if the instance has at least one unconnected port segment.

signals property

signals: Dict[str, SignalArray]

A dictionary with all signals currently present on all ports of this instance.

is_blackbox property

is_blackbox: bool

Flag indicating whether the instance represents neither a primitive element nor a module instance.

If True, this instance does not have a module definition, and is also not a basic component (i.e. a primitive gate instance) from the internal gate library, such as a gate or flip-flop.

a_width property

a_width: PositiveInt

Width of the gate's A port.

b_width property

b_width: PositiveInt

Width of the gate's B port.

is_sequential property

is_sequential: bool

Whether instances of this gate are considered sequential gates.

False for combinational gates, such as AND gates or arithmetic gates. True for flip-flops and latches.

output_port property

output_port: Port[Instance]

The output port of the gate.

data_width property

data_width: int

The data width of this instance.

Defaults to the data width of the output port. Can be overwritten in extended classes.

In contrast to self.width, which is used for the creation and initialization, this property is linked to the data width of the output port. This property is useful when the data width of the output port can be changed.

input_port property

input_port: Port[Instance]

The input port of the gate.

clk_polarity property writable

clk_polarity: Signal

Which clock edge activates the flip-flop. Default is Signal.HIGH, i.e. rising edge.

clk_port property

clk_port: Port[Instance]

The clock port of the gate.

has_en property

has_en: bool

Whether this DFF instance has an EN (enable) port.

has_rst property

has_rst: bool

Whether this DFF instance has an RST (reset) port.

scan_ff_equivalent property

scan_ff_equivalent: Type[ScanDFF]

Returns the Scan-FF type equivalent for normal FF and the FF type equivalent for Scan-FF.

en_polarity property writable

en_polarity: Signal

Which EN-signal level enables writing on the data storage. Default is Signal.HIGH.

en_port property

en_port: Port[Instance]

The enable port of the gate.

en_signal property

en_signal: Signal

The enable signal of the gate.

change_mutability

change_mutability(is_now_locked: bool, recursive: bool = False) -> Self

Change the mutability status of this instance and optionally its ports.

This method allows setting whether this instance can be modified or not. If recursive is set to True, it also applies the same mutability status to all ports of this instance.

Parameters:

  • is_now_locked

    (bool) –

    The new mutability status for this instance.

  • recursive

    (bool, default: False ) –

    Whether to apply the change recursively to its ports. Defaults to False.

evaluate

evaluate() -> None

Evaluates the gate's output signal.

This method is called when the gate's input signals change, and it updates the gate's output signal accordingly.

all_connections

all_connections(
    include_unconnected: bool,
) -> Dict[str, Dict[int, WireSegmentPath]]

Returns a dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port.

Parameters:

  • include_unconnected

    (bool) –

    Whether to include unconnected ports in the result.

Returns:

connect

connect(
    port_name: str,
    ws_path: Optional[WireSegmentPath],
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add connections to the specified port of this instance.

This method can establish multiple connections if a range of indices is provided.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection(s) should be established.

  • ws_path

    (Optional[WireSegmentPath]) –

    The path of the wire segment that will be connected to this port. If None, the associated port (segment) remains unconnected.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

Raises:

  • ObjectLockedError

    If this instance is currently locked, and no connection can be made.

disconnect

disconnect(port_name: str, index: Optional[int] = None) -> None

Remove an existing connection from a specified port of this instance.

This method disconnects the wire segment at the given index within the specified port_name.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be removed.

  • index

    (Optional[int], default: None ) –

    The bit index within the port for this disconnection. Defaults to None, which completely disconnects the port.

Raises:

get_connection

get_connection(
    port_name: str, index: Optional[NonNegativeInt] = None
) -> Union[WireSegmentPath, Dict[int, WireSegmentPath], None]

Retrieve the connection path associated with a specified port and bit index.

If index is provided, this method returns the wire segment path connected to that specific bit within the port. Otherwise, it returns all connections for the given port as a dictionary mapping indices to WireSegmentPaths.

Parameters:

  • port_name

    (str) –

    The name of the port for which to retrieve the connection(s).

  • index

    (Optional[NonNegativeInt], default: None ) –

    The bit index within the port. Defaults to None.

Returns:

modify_connection

modify_connection(
    port_name: str, ws_path: WireSegmentPath, index: NonNegativeInt = 0
) -> None

Modify an existing connection within a specified port of this instance.

This method updates the wire segment path at the given index within the specified port_name. If the index does not exist yet, it is newly added, changing the width of the port.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be modified.

  • ws_path

    (WireSegmentPath) –

    The new wire segment path for this connection.

  • index

    (NonNegativeInt, default: 0 ) –

    The bit index within the port. Defaults to 0.

connect_modify

connect_modify(
    port_name: str,
    ws_path: WireSegmentPath,
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add a new connection or modify an existing one within the specified port of this instance.

If the connection already exists at the given index and port_name, it will be modified. Otherwise, a new connection is added.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be established or updated.

  • ws_path

    (WireSegmentPath) –

    The path of the wire segment that will be connected to this port.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

tie_port

tie_port(name: str, index: NonNegativeInt, sig_value: LogicLevel) -> None

Set a constant signal value for the specified port and bit index.

If the specified port does not exist, an error message is logged and the function returns False. Otherwise, the method tries to set the constant signal value for that port and returns True if successful.

Does not work for instance output ports, as they are always driven by their parent instances.

Parameters:

  • name

    (str) –

    The name of the port.

  • index

    (NonNegativeInt) –

    The bit index within the port.

  • sig_value

    (LogicLevel) –

    The constant signal value to be set ('0', '1', or 'Z').

Raises:

  • ObjectNotFoundError

    If no such port or port segment exists.

  • AlreadyConnectedError

    (raised by: PortSegment.tie_signal) If this segment is belongs to a load port and is already connected to a wire, from which it receives its value.

  • InvalidDirectionError

    (raised by: PortSegment.tie_signal) If this port segment belongs to an instance output port, which is driven by the instance inputs and the instance's internal logic.

  • InvalidSignalError

    (raised by: PortSegment.tie_signal) If an invalid value is provided.

has_tied_ports

has_tied_ports() -> bool

Checks the ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any ports of this instance are tied to constant values. False otherwise, i.e. all ports are connected to wires.

has_tied_inputs

has_tied_inputs() -> bool

Checks the input ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any input ports of this instance are tied to constant values. False otherwise, i.e. all input ports are connected to wires.

has_tied_outputs

has_tied_outputs() -> bool

Checks the output ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any output ports of this instance are tied to constant values. False otherwise, i.e. all output ports are connected to wires.

update_signedness

update_signedness(port_name: str) -> None

Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

Parameters:

  • port_name

    (str) –

    The name of the port, of which the signedness value is retrieved.

split

split() -> Dict[NonNegativeInt, Self]

Performs a bit-wise split on this instance.

If this instance supports splitting and has a data width of n bit, this method splits this instance into n 1-bit instances. This works for instances, where each output bit depends only on the corresponding input bit(s), e.g. an AND gate or a D-Flipflop.

Returns:

  • Dict[NonNegativeInt, Self]

    Dict[int, Instance]: An n-bit large dictionary, where each key conforms to a bit of the original instance, and each value is an 1-bit instance representing the corresponding "slice" of the original instance.

Raises:

  • SplittingUnsupportedError

    If this instance does not support splitting. Happens for any gate or instance whose behavior depends on the whole bus, and splitting would make it lose its meaning.

p2v

p2v(
    port: ANY_PORT,
    exclude_indices: Optional[List[int]] = None,
    include_indices: Optional[List[int]] = None,
) -> str

Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a Port object and converts them to their corresponding Verilog signal structure (p2v -> Port to Verilog signal syntax). For each segment of the port, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port is set to a constant, the corresponding constant wire segment placeholder is used instead. Port segments can be excluded from the conversion by providing a list of indices to the exclude_indices parameter, indicating which segments should be excluded from the conversion (e.g. segments that are known to be unconnected). Vice versa, only a certain subset of the port's segments may be converted to Verilog syntax, if include_indices is a given list of port indices. All indices not present in the list will be excluded from the conversion.

Parameters:

  • port

    (Port) –

    The Port object to convert.

  • exclude_indices

    (List[int], default: None ) –

    A list of indices to exclude from the conversion. Defaults to None.

  • include_indices

    (List[int], default: None ) –

    A list of indices (i.e. port slices) to include only for the conversion. Defaults to None.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

  • ObjectNotFoundError

    If the wire connected to a certain port segment could not be found.

  • UnsupportedOperationError

    If both exclude_indices and include_indices are specified. Only one of both may be given when calling this method.

ps2v

Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a PortSegment dictionary and converts them to their corresponding Verilog signal structure (ps2v -> PortSegment to Verilog signal syntax). For each segment, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port segment is set to a constant, the corresponding constant wire segment placeholder is used instead.

Parameters:

  • ps_dict

    (Dict[int, PortSegment]) –

    The PortSegment dictionary to convert. Each key (int) conforms to the index of the associated PortSegment object.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

set

set(
    port_name: str,
    new_signal: SignalOrLogicLevel,
    idx: Union[int, List[int]] = 0,
) -> None

Sets the signal on a port.

Parameters:

  • port_name

    (str) –

    The name of the port to set the signal on.

  • new_signal

    (Signal) –

    The new signal value.

  • idx

    (Union[int, List[int]], default: 0 ) –

    The index (or indices) to apply the given signal to. Can either be an integer (single index to set) or an iterable of integers (e.g. a list of indices). For every integer of the iterable the signal value of the corresponding port index is set to the given new_signal. Defaults to 0.

Example

from netlist_carpentry.utils.gate_factory import and_gate module = Module(name='m') a = module.create_port('a', 'input', width=6) instance = and_gate(module, 'inst', A=a)

This sets the value of bit 0 of port A to HIGH

instance.set('A', 1, 0) instance.ports['A'].signal_str 'xxxxx1'

This sets the value of bits 1, 3 and 5 of port A to LOW, leaving the other bits as they already are.

instance.set('A', 0, [1, 3, 5]) instance.ports['A'].signal_str '0x0x01'

set_clk

set_clk(new_signal: SignalOrLogicLevel) -> None

Sets the clock signal.

Parameters:

  • new_signal

    (Signal) –

    The new clock signal value.

get_scanff

get_scanff() -> ScanDFF

Creates and returns a scan-DFF version of this DFF, copying all parameters of this DFF.

No connections are copied however, and the instance initially does not belong to any module.

set_en

set_en(new_signal: SignalOrLogicLevel) -> None

Sets the enable signal.

Parameters:

  • new_signal

    (Signal) –

    The new enable signal value.

ADFFE

Bases: DFFE, ADFF

Asynchronously resettable DFF with enable port.

Methods:

  • change_mutability

    Change the mutability status of this instance and optionally its ports.

  • evaluate

    Evaluates the gate's output signal.

  • all_connections

    Returns a dictionary mapping port names to their corresponding connection paths.

  • connect

    Add connections to the specified port of this instance.

  • disconnect

    Remove an existing connection from a specified port of this instance.

  • get_connection

    Retrieve the connection path associated with a specified port and bit index.

  • modify_connection

    Modify an existing connection within a specified port of this instance.

  • connect_modify

    Add a new connection or modify an existing one within the specified port of this instance.

  • tie_port

    Set a constant signal value for the specified port and bit index.

  • has_tied_ports

    Checks the ports of this instance whether any are tied to constant values.

  • has_tied_inputs

    Checks the input ports of this instance whether any are tied to constant values.

  • has_tied_outputs

    Checks the output ports of this instance whether any are tied to constant values.

  • update_signedness

    Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

  • split

    Performs a bit-wise split on this instance.

  • p2v

    Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

  • ps2v

    Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

  • set

    Sets the signal on a port.

  • set_clk

    Sets the clock signal.

  • get_scanff

    Creates and returns a scan-DFF version of this DFF, copying all parameters of this DFF.

  • set_rst

    Sets the reset signal.

  • set_en

    Sets the enable signal.

Attributes:

name instance-attribute

name: str

The name of the element.

!!! Do not modify this variable after instantiating it. Use NetlistElement.set_name() instead. Modifying this variable might lead to inconsistencies later on.

metadata class-attribute instance-attribute

Metadata of a netlist element.

Can be user-defined, or e. g. by Yosys (such as src for the HDL source). Is also grouped by categories, i.e. all metadata from Yosys can be accessed via Module.metadata["yosys"], or via Module.metadata.yosys, which both return a dictionary of all metadata. Read the documentation of MetaDataMixin for more information.

path property

Returns the InstancePath of the netlist element.

The InstancePath object is constructed using the element's type and its raw hierarchical path.

Returns:

  • InstancePath ( InstancePath ) –

    The hierarchical path of the netlist element.

type property

type: EType

The type of the element, which is an instance.

hierarchy_level property

hierarchy_level: int

The level of hierarchy of the element in the design.

The hierarchy level is the number of separators in the element's raw path. For example, a top-level instance has a hierarchy level of 0, while a direct submodule instance has a hierarchy level of 1.

Returns:

  • int ( int ) –

    The hierarchy level of the element.

has_parent property

has_parent: bool

Whether this object has a parent.

circuit property

circuit: 'Circuit'

The circuit object to which this netlist element belongs to.

  • For a module, returns the circuit to which the module belongs.
  • For any other netlist element, recursively returns the circuit of the parent, which ultimately leads to a module, to which the netlist element belongs.

Raises:

  • ParentNotFoundError

    If a parent cannot be resolved somewhere in the hierarchical chain.

  • ObjectNotFoundError

    If for a module no circuit is set.

has_circuit property

has_circuit: bool

Whether this netlist element has a defined circuit it belongs to.

Tries to access self.circuit and returns whether the call was successful. Can be used instead of a try-except clause around the call to NetlistElement.circuit.

locked property

locked: bool

True if this NetlistElement instance is locked (i.e. it is currently structurally unchangeable), False if it is mutable.

Can be changed via NetlistElement.change_mutability(bool).

Immutability is used to prevent accidental changes to the design.

is_placeholder_instance property

is_placeholder_instance: bool

A placeholder represents an element that does not have a specific path.

True if this NetlistElement instance represents a placeholder, False otherwise.

can_carry_signal property

can_carry_signal: bool

Whether this exact object is able to receive, pass or hold signal values.

True for ports (as they drive or receive values) and wires (as they pass the signals from driver to load ports) as well as their respective segments. False for instances and modules.

connections property

connections: Dict[str, Dict[int, WireSegmentPath]]

A dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port. Elements with no connection (i.e. the path is None) are excluded. In case these are needed, use Instance.get_connections() instead.

Example

{ 'port1': {1: WireSegmentPath('path/to/element1'), 2: WireSegmentPath('path/to/element2')}, 'port2': {1: WireSegmentPath('path/to/element3')} }

connection_str_paths property

connection_str_paths: Dict[str, Dict[int, str]]

Returns a dictionary mapping port names to their corresponding connection paths as strings.

The keys are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are the raw string paths.

Example

{ 'port1': {0: 'path.to.element1', 1: 'path.to.element2'}, 'port2': {0: 'path.to.element3'} }

ports property

A dictionary mapping port names to their corresponding Port objects.

The keys of the dictionary are the names of the ports. The values are Port objects representing the ports.

Returns:

input_ports property

input_ports: Tuple[Port[Instance], ...]

Returns a tuple of input ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as inputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the input ports.

output_ports property

output_ports: Tuple[Port[Instance], ...]

Returns a tuple of output ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as outputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the output ports.

has_unconnected_port_segments property

has_unconnected_port_segments: bool

Returns True if the instance has at least one unconnected port segment.

signals property

signals: Dict[str, SignalArray]

A dictionary with all signals currently present on all ports of this instance.

is_blackbox property

is_blackbox: bool

Flag indicating whether the instance represents neither a primitive element nor a module instance.

If True, this instance does not have a module definition, and is also not a basic component (i.e. a primitive gate instance) from the internal gate library, such as a gate or flip-flop.

a_width property

a_width: PositiveInt

Width of the gate's A port.

b_width property

b_width: PositiveInt

Width of the gate's B port.

is_sequential property

is_sequential: bool

Whether instances of this gate are considered sequential gates.

False for combinational gates, such as AND gates or arithmetic gates. True for flip-flops and latches.

output_port property

output_port: Port[Instance]

The output port of the gate.

data_width property

data_width: int

The data width of this instance.

Defaults to the data width of the output port. Can be overwritten in extended classes.

In contrast to self.width, which is used for the creation and initialization, this property is linked to the data width of the output port. This property is useful when the data width of the output port can be changed.

input_port property

input_port: Port[Instance]

The input port of the gate.

clk_polarity property writable

clk_polarity: Signal

Which clock edge activates the flip-flop. Default is Signal.HIGH, i.e. rising edge.

clk_port property

clk_port: Port[Instance]

The clock port of the gate.

has_en property

has_en: bool

Whether this DFF instance has an EN (enable) port.

has_rst property

has_rst: bool

Whether this DFF instance has an RST (reset) port.

scan_ff_equivalent property

scan_ff_equivalent: Type[ScanDFF]

Returns the Scan-FF type equivalent for normal FF and the FF type equivalent for Scan-FF.

rst_polarity property writable

rst_polarity: Signal

Which reset level resets the flip-flop. Default is Signal.HIGH: the flipflop is in reset, if the reset signal is HIGH.

rst_val_int property writable

rst_val_int: int

Reset value of the flip-flop as integer. Default is 0.

rst_port property

rst_port: Port[Instance]

The reset port of the gate.

rst_val property

rst_val: SignalArray

The value of the flipflop during and after reset. Default is Signal.LOW, i.e. the initial flipflop state is 0 by default.

in_reset property

in_reset: bool

True if the gate is currently in reset, False otherwise.

en_polarity property writable

en_polarity: Signal

Which EN-signal level enables writing on the data storage. Default is Signal.HIGH.

en_port property

en_port: Port[Instance]

The enable port of the gate.

en_signal property

en_signal: Signal

The enable signal of the gate.

change_mutability

change_mutability(is_now_locked: bool, recursive: bool = False) -> Self

Change the mutability status of this instance and optionally its ports.

This method allows setting whether this instance can be modified or not. If recursive is set to True, it also applies the same mutability status to all ports of this instance.

Parameters:

  • is_now_locked

    (bool) –

    The new mutability status for this instance.

  • recursive

    (bool, default: False ) –

    Whether to apply the change recursively to its ports. Defaults to False.

evaluate

evaluate() -> None

Evaluates the gate's output signal.

This method is called when the gate's input signals change, and it updates the gate's output signal accordingly.

all_connections

all_connections(
    include_unconnected: bool,
) -> Dict[str, Dict[int, WireSegmentPath]]

Returns a dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port.

Parameters:

  • include_unconnected

    (bool) –

    Whether to include unconnected ports in the result.

Returns:

connect

connect(
    port_name: str,
    ws_path: Optional[WireSegmentPath],
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add connections to the specified port of this instance.

This method can establish multiple connections if a range of indices is provided.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection(s) should be established.

  • ws_path

    (Optional[WireSegmentPath]) –

    The path of the wire segment that will be connected to this port. If None, the associated port (segment) remains unconnected.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

Raises:

  • ObjectLockedError

    If this instance is currently locked, and no connection can be made.

disconnect

disconnect(port_name: str, index: Optional[int] = None) -> None

Remove an existing connection from a specified port of this instance.

This method disconnects the wire segment at the given index within the specified port_name.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be removed.

  • index

    (Optional[int], default: None ) –

    The bit index within the port for this disconnection. Defaults to None, which completely disconnects the port.

Raises:

get_connection

get_connection(
    port_name: str, index: Optional[NonNegativeInt] = None
) -> Union[WireSegmentPath, Dict[int, WireSegmentPath], None]

Retrieve the connection path associated with a specified port and bit index.

If index is provided, this method returns the wire segment path connected to that specific bit within the port. Otherwise, it returns all connections for the given port as a dictionary mapping indices to WireSegmentPaths.

Parameters:

  • port_name

    (str) –

    The name of the port for which to retrieve the connection(s).

  • index

    (Optional[NonNegativeInt], default: None ) –

    The bit index within the port. Defaults to None.

Returns:

modify_connection

modify_connection(
    port_name: str, ws_path: WireSegmentPath, index: NonNegativeInt = 0
) -> None

Modify an existing connection within a specified port of this instance.

This method updates the wire segment path at the given index within the specified port_name. If the index does not exist yet, it is newly added, changing the width of the port.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be modified.

  • ws_path

    (WireSegmentPath) –

    The new wire segment path for this connection.

  • index

    (NonNegativeInt, default: 0 ) –

    The bit index within the port. Defaults to 0.

connect_modify

connect_modify(
    port_name: str,
    ws_path: WireSegmentPath,
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add a new connection or modify an existing one within the specified port of this instance.

If the connection already exists at the given index and port_name, it will be modified. Otherwise, a new connection is added.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be established or updated.

  • ws_path

    (WireSegmentPath) –

    The path of the wire segment that will be connected to this port.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

tie_port

tie_port(name: str, index: NonNegativeInt, sig_value: LogicLevel) -> None

Set a constant signal value for the specified port and bit index.

If the specified port does not exist, an error message is logged and the function returns False. Otherwise, the method tries to set the constant signal value for that port and returns True if successful.

Does not work for instance output ports, as they are always driven by their parent instances.

Parameters:

  • name

    (str) –

    The name of the port.

  • index

    (NonNegativeInt) –

    The bit index within the port.

  • sig_value

    (LogicLevel) –

    The constant signal value to be set ('0', '1', or 'Z').

Raises:

  • ObjectNotFoundError

    If no such port or port segment exists.

  • AlreadyConnectedError

    (raised by: PortSegment.tie_signal) If this segment is belongs to a load port and is already connected to a wire, from which it receives its value.

  • InvalidDirectionError

    (raised by: PortSegment.tie_signal) If this port segment belongs to an instance output port, which is driven by the instance inputs and the instance's internal logic.

  • InvalidSignalError

    (raised by: PortSegment.tie_signal) If an invalid value is provided.

has_tied_ports

has_tied_ports() -> bool

Checks the ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any ports of this instance are tied to constant values. False otherwise, i.e. all ports are connected to wires.

has_tied_inputs

has_tied_inputs() -> bool

Checks the input ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any input ports of this instance are tied to constant values. False otherwise, i.e. all input ports are connected to wires.

has_tied_outputs

has_tied_outputs() -> bool

Checks the output ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any output ports of this instance are tied to constant values. False otherwise, i.e. all output ports are connected to wires.

update_signedness

update_signedness(port_name: str) -> None

Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

Parameters:

  • port_name

    (str) –

    The name of the port, of which the signedness value is retrieved.

split

split() -> Dict[NonNegativeInt, Self]

Performs a bit-wise split on this instance.

If this instance supports splitting and has a data width of n bit, this method splits this instance into n 1-bit instances. This works for instances, where each output bit depends only on the corresponding input bit(s), e.g. an AND gate or a D-Flipflop.

Returns:

  • Dict[NonNegativeInt, Self]

    Dict[int, Instance]: An n-bit large dictionary, where each key conforms to a bit of the original instance, and each value is an 1-bit instance representing the corresponding "slice" of the original instance.

Raises:

  • SplittingUnsupportedError

    If this instance does not support splitting. Happens for any gate or instance whose behavior depends on the whole bus, and splitting would make it lose its meaning.

p2v

p2v(
    port: ANY_PORT,
    exclude_indices: Optional[List[int]] = None,
    include_indices: Optional[List[int]] = None,
) -> str

Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a Port object and converts them to their corresponding Verilog signal structure (p2v -> Port to Verilog signal syntax). For each segment of the port, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port is set to a constant, the corresponding constant wire segment placeholder is used instead. Port segments can be excluded from the conversion by providing a list of indices to the exclude_indices parameter, indicating which segments should be excluded from the conversion (e.g. segments that are known to be unconnected). Vice versa, only a certain subset of the port's segments may be converted to Verilog syntax, if include_indices is a given list of port indices. All indices not present in the list will be excluded from the conversion.

Parameters:

  • port

    (Port) –

    The Port object to convert.

  • exclude_indices

    (List[int], default: None ) –

    A list of indices to exclude from the conversion. Defaults to None.

  • include_indices

    (List[int], default: None ) –

    A list of indices (i.e. port slices) to include only for the conversion. Defaults to None.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

  • ObjectNotFoundError

    If the wire connected to a certain port segment could not be found.

  • UnsupportedOperationError

    If both exclude_indices and include_indices are specified. Only one of both may be given when calling this method.

ps2v

Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a PortSegment dictionary and converts them to their corresponding Verilog signal structure (ps2v -> PortSegment to Verilog signal syntax). For each segment, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port segment is set to a constant, the corresponding constant wire segment placeholder is used instead.

Parameters:

  • ps_dict

    (Dict[int, PortSegment]) –

    The PortSegment dictionary to convert. Each key (int) conforms to the index of the associated PortSegment object.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

set

set(
    port_name: str,
    new_signal: SignalOrLogicLevel,
    idx: Union[int, List[int]] = 0,
) -> None

Sets the signal on a port.

Parameters:

  • port_name

    (str) –

    The name of the port to set the signal on.

  • new_signal

    (Signal) –

    The new signal value.

  • idx

    (Union[int, List[int]], default: 0 ) –

    The index (or indices) to apply the given signal to. Can either be an integer (single index to set) or an iterable of integers (e.g. a list of indices). For every integer of the iterable the signal value of the corresponding port index is set to the given new_signal. Defaults to 0.

Example

from netlist_carpentry.utils.gate_factory import and_gate module = Module(name='m') a = module.create_port('a', 'input', width=6) instance = and_gate(module, 'inst', A=a)

This sets the value of bit 0 of port A to HIGH

instance.set('A', 1, 0) instance.ports['A'].signal_str 'xxxxx1'

This sets the value of bits 1, 3 and 5 of port A to LOW, leaving the other bits as they already are.

instance.set('A', 0, [1, 3, 5]) instance.ports['A'].signal_str '0x0x01'

set_clk

set_clk(new_signal: SignalOrLogicLevel) -> None

Sets the clock signal.

Parameters:

  • new_signal

    (Signal) –

    The new clock signal value.

get_scanff

get_scanff() -> ScanDFF

Creates and returns a scan-DFF version of this DFF, copying all parameters of this DFF.

No connections are copied however, and the instance initially does not belong to any module.

set_rst

set_rst(new_signal: SignalOrLogicLevel) -> None

Sets the reset signal.

Parameters:

  • new_signal

    (Signal) –

    The new reset signal value.

set_en

set_en(new_signal: SignalOrLogicLevel) -> None

Sets the enable signal.

Parameters:

  • new_signal

    (Signal) –

    The new enable signal value.

SDFF

Bases: RstMixin, DFF

Synchronously resettable DFF.

Methods:

  • change_mutability

    Change the mutability status of this instance and optionally its ports.

  • evaluate

    Evaluates the gate's output signal.

  • all_connections

    Returns a dictionary mapping port names to their corresponding connection paths.

  • connect

    Add connections to the specified port of this instance.

  • disconnect

    Remove an existing connection from a specified port of this instance.

  • get_connection

    Retrieve the connection path associated with a specified port and bit index.

  • modify_connection

    Modify an existing connection within a specified port of this instance.

  • connect_modify

    Add a new connection or modify an existing one within the specified port of this instance.

  • tie_port

    Set a constant signal value for the specified port and bit index.

  • has_tied_ports

    Checks the ports of this instance whether any are tied to constant values.

  • has_tied_inputs

    Checks the input ports of this instance whether any are tied to constant values.

  • has_tied_outputs

    Checks the output ports of this instance whether any are tied to constant values.

  • update_signedness

    Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

  • split

    Performs a bit-wise split on this instance.

  • p2v

    Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

  • ps2v

    Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

  • set

    Sets the signal on a port.

  • set_clk

    Sets the clock signal.

  • get_scanff

    Creates and returns a scan-DFF version of this DFF, copying all parameters of this DFF.

Attributes:

name instance-attribute

name: str

The name of the element.

!!! Do not modify this variable after instantiating it. Use NetlistElement.set_name() instead. Modifying this variable might lead to inconsistencies later on.

metadata class-attribute instance-attribute

Metadata of a netlist element.

Can be user-defined, or e. g. by Yosys (such as src for the HDL source). Is also grouped by categories, i.e. all metadata from Yosys can be accessed via Module.metadata["yosys"], or via Module.metadata.yosys, which both return a dictionary of all metadata. Read the documentation of MetaDataMixin for more information.

path property

Returns the InstancePath of the netlist element.

The InstancePath object is constructed using the element's type and its raw hierarchical path.

Returns:

  • InstancePath ( InstancePath ) –

    The hierarchical path of the netlist element.

type property

type: EType

The type of the element, which is an instance.

hierarchy_level property

hierarchy_level: int

The level of hierarchy of the element in the design.

The hierarchy level is the number of separators in the element's raw path. For example, a top-level instance has a hierarchy level of 0, while a direct submodule instance has a hierarchy level of 1.

Returns:

  • int ( int ) –

    The hierarchy level of the element.

has_parent property

has_parent: bool

Whether this object has a parent.

circuit property

circuit: 'Circuit'

The circuit object to which this netlist element belongs to.

  • For a module, returns the circuit to which the module belongs.
  • For any other netlist element, recursively returns the circuit of the parent, which ultimately leads to a module, to which the netlist element belongs.

Raises:

  • ParentNotFoundError

    If a parent cannot be resolved somewhere in the hierarchical chain.

  • ObjectNotFoundError

    If for a module no circuit is set.

has_circuit property

has_circuit: bool

Whether this netlist element has a defined circuit it belongs to.

Tries to access self.circuit and returns whether the call was successful. Can be used instead of a try-except clause around the call to NetlistElement.circuit.

locked property

locked: bool

True if this NetlistElement instance is locked (i.e. it is currently structurally unchangeable), False if it is mutable.

Can be changed via NetlistElement.change_mutability(bool).

Immutability is used to prevent accidental changes to the design.

is_placeholder_instance property

is_placeholder_instance: bool

A placeholder represents an element that does not have a specific path.

True if this NetlistElement instance represents a placeholder, False otherwise.

can_carry_signal property

can_carry_signal: bool

Whether this exact object is able to receive, pass or hold signal values.

True for ports (as they drive or receive values) and wires (as they pass the signals from driver to load ports) as well as their respective segments. False for instances and modules.

connections property

connections: Dict[str, Dict[int, WireSegmentPath]]

A dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port. Elements with no connection (i.e. the path is None) are excluded. In case these are needed, use Instance.get_connections() instead.

Example

{ 'port1': {1: WireSegmentPath('path/to/element1'), 2: WireSegmentPath('path/to/element2')}, 'port2': {1: WireSegmentPath('path/to/element3')} }

connection_str_paths property

connection_str_paths: Dict[str, Dict[int, str]]

Returns a dictionary mapping port names to their corresponding connection paths as strings.

The keys are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are the raw string paths.

Example

{ 'port1': {0: 'path.to.element1', 1: 'path.to.element2'}, 'port2': {0: 'path.to.element3'} }

ports property

A dictionary mapping port names to their corresponding Port objects.

The keys of the dictionary are the names of the ports. The values are Port objects representing the ports.

Returns:

input_ports property

input_ports: Tuple[Port[Instance], ...]

Returns a tuple of input ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as inputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the input ports.

output_ports property

output_ports: Tuple[Port[Instance], ...]

Returns a tuple of output ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as outputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the output ports.

has_unconnected_port_segments property

has_unconnected_port_segments: bool

Returns True if the instance has at least one unconnected port segment.

signals property

signals: Dict[str, SignalArray]

A dictionary with all signals currently present on all ports of this instance.

is_blackbox property

is_blackbox: bool

Flag indicating whether the instance represents neither a primitive element nor a module instance.

If True, this instance does not have a module definition, and is also not a basic component (i.e. a primitive gate instance) from the internal gate library, such as a gate or flip-flop.

a_width property

a_width: PositiveInt

Width of the gate's A port.

b_width property

b_width: PositiveInt

Width of the gate's B port.

is_sequential property

is_sequential: bool

Whether instances of this gate are considered sequential gates.

False for combinational gates, such as AND gates or arithmetic gates. True for flip-flops and latches.

output_port property

output_port: Port[Instance]

The output port of the gate.

data_width property

data_width: int

The data width of this instance.

Defaults to the data width of the output port. Can be overwritten in extended classes.

In contrast to self.width, which is used for the creation and initialization, this property is linked to the data width of the output port. This property is useful when the data width of the output port can be changed.

input_port property

input_port: Port[Instance]

The input port of the gate.

clk_polarity property writable

clk_polarity: Signal

Which clock edge activates the flip-flop. Default is Signal.HIGH, i.e. rising edge.

clk_port property

clk_port: Port[Instance]

The clock port of the gate.

has_en property

has_en: bool

Whether this DFF instance has an EN (enable) port.

has_rst property

has_rst: bool

Whether this DFF instance has an RST (reset) port.

scan_ff_equivalent property

scan_ff_equivalent: Type[ScanDFF]

Returns the Scan-FF type equivalent for normal FF and the FF type equivalent for Scan-FF.

rst_polarity property writable

rst_polarity: Signal

Which reset level resets the flip-flop. Default is Signal.HIGH: the flipflop is in reset, if the reset signal is HIGH.

rst_val_int property writable

rst_val_int: int

Reset value of the flip-flop as integer. Default is 0.

rst_port property

rst_port: Port[Instance]

The reset port of the gate.

rst_val property

rst_val: SignalArray

The value of the flipflop during and after reset. Default is Signal.LOW, i.e. the initial flipflop state is 0 by default.

in_reset property

in_reset: bool

True if the gate is currently in reset, False otherwise.

change_mutability

change_mutability(is_now_locked: bool, recursive: bool = False) -> Self

Change the mutability status of this instance and optionally its ports.

This method allows setting whether this instance can be modified or not. If recursive is set to True, it also applies the same mutability status to all ports of this instance.

Parameters:

  • is_now_locked

    (bool) –

    The new mutability status for this instance.

  • recursive

    (bool, default: False ) –

    Whether to apply the change recursively to its ports. Defaults to False.

evaluate

evaluate() -> None

Evaluates the gate's output signal.

This method is called when the gate's input signals change, and it updates the gate's output signal accordingly.

all_connections

all_connections(
    include_unconnected: bool,
) -> Dict[str, Dict[int, WireSegmentPath]]

Returns a dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port.

Parameters:

  • include_unconnected

    (bool) –

    Whether to include unconnected ports in the result.

Returns:

connect

connect(
    port_name: str,
    ws_path: Optional[WireSegmentPath],
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add connections to the specified port of this instance.

This method can establish multiple connections if a range of indices is provided.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection(s) should be established.

  • ws_path

    (Optional[WireSegmentPath]) –

    The path of the wire segment that will be connected to this port. If None, the associated port (segment) remains unconnected.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

Raises:

  • ObjectLockedError

    If this instance is currently locked, and no connection can be made.

disconnect

disconnect(port_name: str, index: Optional[int] = None) -> None

Remove an existing connection from a specified port of this instance.

This method disconnects the wire segment at the given index within the specified port_name.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be removed.

  • index

    (Optional[int], default: None ) –

    The bit index within the port for this disconnection. Defaults to None, which completely disconnects the port.

Raises:

get_connection

get_connection(
    port_name: str, index: Optional[NonNegativeInt] = None
) -> Union[WireSegmentPath, Dict[int, WireSegmentPath], None]

Retrieve the connection path associated with a specified port and bit index.

If index is provided, this method returns the wire segment path connected to that specific bit within the port. Otherwise, it returns all connections for the given port as a dictionary mapping indices to WireSegmentPaths.

Parameters:

  • port_name

    (str) –

    The name of the port for which to retrieve the connection(s).

  • index

    (Optional[NonNegativeInt], default: None ) –

    The bit index within the port. Defaults to None.

Returns:

modify_connection

modify_connection(
    port_name: str, ws_path: WireSegmentPath, index: NonNegativeInt = 0
) -> None

Modify an existing connection within a specified port of this instance.

This method updates the wire segment path at the given index within the specified port_name. If the index does not exist yet, it is newly added, changing the width of the port.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be modified.

  • ws_path

    (WireSegmentPath) –

    The new wire segment path for this connection.

  • index

    (NonNegativeInt, default: 0 ) –

    The bit index within the port. Defaults to 0.

connect_modify

connect_modify(
    port_name: str,
    ws_path: WireSegmentPath,
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add a new connection or modify an existing one within the specified port of this instance.

If the connection already exists at the given index and port_name, it will be modified. Otherwise, a new connection is added.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be established or updated.

  • ws_path

    (WireSegmentPath) –

    The path of the wire segment that will be connected to this port.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

tie_port

tie_port(name: str, index: NonNegativeInt, sig_value: LogicLevel) -> None

Set a constant signal value for the specified port and bit index.

If the specified port does not exist, an error message is logged and the function returns False. Otherwise, the method tries to set the constant signal value for that port and returns True if successful.

Does not work for instance output ports, as they are always driven by their parent instances.

Parameters:

  • name

    (str) –

    The name of the port.

  • index

    (NonNegativeInt) –

    The bit index within the port.

  • sig_value

    (LogicLevel) –

    The constant signal value to be set ('0', '1', or 'Z').

Raises:

  • ObjectNotFoundError

    If no such port or port segment exists.

  • AlreadyConnectedError

    (raised by: PortSegment.tie_signal) If this segment is belongs to a load port and is already connected to a wire, from which it receives its value.

  • InvalidDirectionError

    (raised by: PortSegment.tie_signal) If this port segment belongs to an instance output port, which is driven by the instance inputs and the instance's internal logic.

  • InvalidSignalError

    (raised by: PortSegment.tie_signal) If an invalid value is provided.

has_tied_ports

has_tied_ports() -> bool

Checks the ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any ports of this instance are tied to constant values. False otherwise, i.e. all ports are connected to wires.

has_tied_inputs

has_tied_inputs() -> bool

Checks the input ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any input ports of this instance are tied to constant values. False otherwise, i.e. all input ports are connected to wires.

has_tied_outputs

has_tied_outputs() -> bool

Checks the output ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any output ports of this instance are tied to constant values. False otherwise, i.e. all output ports are connected to wires.

update_signedness

update_signedness(port_name: str) -> None

Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

Parameters:

  • port_name

    (str) –

    The name of the port, of which the signedness value is retrieved.

split

split() -> Dict[NonNegativeInt, Self]

Performs a bit-wise split on this instance.

If this instance supports splitting and has a data width of n bit, this method splits this instance into n 1-bit instances. This works for instances, where each output bit depends only on the corresponding input bit(s), e.g. an AND gate or a D-Flipflop.

Returns:

  • Dict[NonNegativeInt, Self]

    Dict[int, Instance]: An n-bit large dictionary, where each key conforms to a bit of the original instance, and each value is an 1-bit instance representing the corresponding "slice" of the original instance.

Raises:

  • SplittingUnsupportedError

    If this instance does not support splitting. Happens for any gate or instance whose behavior depends on the whole bus, and splitting would make it lose its meaning.

p2v

p2v(
    port: ANY_PORT,
    exclude_indices: Optional[List[int]] = None,
    include_indices: Optional[List[int]] = None,
) -> str

Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a Port object and converts them to their corresponding Verilog signal structure (p2v -> Port to Verilog signal syntax). For each segment of the port, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port is set to a constant, the corresponding constant wire segment placeholder is used instead. Port segments can be excluded from the conversion by providing a list of indices to the exclude_indices parameter, indicating which segments should be excluded from the conversion (e.g. segments that are known to be unconnected). Vice versa, only a certain subset of the port's segments may be converted to Verilog syntax, if include_indices is a given list of port indices. All indices not present in the list will be excluded from the conversion.

Parameters:

  • port

    (Port) –

    The Port object to convert.

  • exclude_indices

    (List[int], default: None ) –

    A list of indices to exclude from the conversion. Defaults to None.

  • include_indices

    (List[int], default: None ) –

    A list of indices (i.e. port slices) to include only for the conversion. Defaults to None.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

  • ObjectNotFoundError

    If the wire connected to a certain port segment could not be found.

  • UnsupportedOperationError

    If both exclude_indices and include_indices are specified. Only one of both may be given when calling this method.

ps2v

Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a PortSegment dictionary and converts them to their corresponding Verilog signal structure (ps2v -> PortSegment to Verilog signal syntax). For each segment, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port segment is set to a constant, the corresponding constant wire segment placeholder is used instead.

Parameters:

  • ps_dict

    (Dict[int, PortSegment]) –

    The PortSegment dictionary to convert. Each key (int) conforms to the index of the associated PortSegment object.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

set

set(
    port_name: str,
    new_signal: SignalOrLogicLevel,
    idx: Union[int, List[int]] = 0,
) -> None

Sets the signal on a port.

Parameters:

  • port_name

    (str) –

    The name of the port to set the signal on.

  • new_signal

    (Signal) –

    The new signal value.

  • idx

    (Union[int, List[int]], default: 0 ) –

    The index (or indices) to apply the given signal to. Can either be an integer (single index to set) or an iterable of integers (e.g. a list of indices). For every integer of the iterable the signal value of the corresponding port index is set to the given new_signal. Defaults to 0.

Example

from netlist_carpentry.utils.gate_factory import and_gate module = Module(name='m') a = module.create_port('a', 'input', width=6) instance = and_gate(module, 'inst', A=a)

This sets the value of bit 0 of port A to HIGH

instance.set('A', 1, 0) instance.ports['A'].signal_str 'xxxxx1'

This sets the value of bits 1, 3 and 5 of port A to LOW, leaving the other bits as they already are.

instance.set('A', 0, [1, 3, 5]) instance.ports['A'].signal_str '0x0x01'

set_clk

set_clk(new_signal: SignalOrLogicLevel) -> None

Sets the clock signal.

Parameters:

  • new_signal

    (Signal) –

    The new clock signal value.

get_scanff

get_scanff() -> ScanDFF

Creates and returns a scan-DFF version of this DFF, copying all parameters of this DFF.

No connections are copied however, and the instance initially does not belong to any module.

SDFFCE

Bases: EnMixin, SDFF

Synchronously resettable DFF with enable port, where the enable signal takes precedence over the reset signal.

Methods:

  • change_mutability

    Change the mutability status of this instance and optionally its ports.

  • evaluate

    Evaluates the gate's output signal.

  • all_connections

    Returns a dictionary mapping port names to their corresponding connection paths.

  • connect

    Add connections to the specified port of this instance.

  • disconnect

    Remove an existing connection from a specified port of this instance.

  • get_connection

    Retrieve the connection path associated with a specified port and bit index.

  • modify_connection

    Modify an existing connection within a specified port of this instance.

  • connect_modify

    Add a new connection or modify an existing one within the specified port of this instance.

  • tie_port

    Set a constant signal value for the specified port and bit index.

  • has_tied_ports

    Checks the ports of this instance whether any are tied to constant values.

  • has_tied_inputs

    Checks the input ports of this instance whether any are tied to constant values.

  • has_tied_outputs

    Checks the output ports of this instance whether any are tied to constant values.

  • update_signedness

    Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

  • split

    Performs a bit-wise split on this instance.

  • p2v

    Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

  • ps2v

    Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

  • set

    Sets the signal on a port.

  • set_clk

    Sets the clock signal.

  • get_scanff

    Creates and returns a scan-DFF version of this DFF, copying all parameters of this DFF.

  • set_en

    Sets the enable signal.

Attributes:

name instance-attribute

name: str

The name of the element.

!!! Do not modify this variable after instantiating it. Use NetlistElement.set_name() instead. Modifying this variable might lead to inconsistencies later on.

metadata class-attribute instance-attribute

Metadata of a netlist element.

Can be user-defined, or e. g. by Yosys (such as src for the HDL source). Is also grouped by categories, i.e. all metadata from Yosys can be accessed via Module.metadata["yosys"], or via Module.metadata.yosys, which both return a dictionary of all metadata. Read the documentation of MetaDataMixin for more information.

path property

Returns the InstancePath of the netlist element.

The InstancePath object is constructed using the element's type and its raw hierarchical path.

Returns:

  • InstancePath ( InstancePath ) –

    The hierarchical path of the netlist element.

type property

type: EType

The type of the element, which is an instance.

hierarchy_level property

hierarchy_level: int

The level of hierarchy of the element in the design.

The hierarchy level is the number of separators in the element's raw path. For example, a top-level instance has a hierarchy level of 0, while a direct submodule instance has a hierarchy level of 1.

Returns:

  • int ( int ) –

    The hierarchy level of the element.

has_parent property

has_parent: bool

Whether this object has a parent.

circuit property

circuit: 'Circuit'

The circuit object to which this netlist element belongs to.

  • For a module, returns the circuit to which the module belongs.
  • For any other netlist element, recursively returns the circuit of the parent, which ultimately leads to a module, to which the netlist element belongs.

Raises:

  • ParentNotFoundError

    If a parent cannot be resolved somewhere in the hierarchical chain.

  • ObjectNotFoundError

    If for a module no circuit is set.

has_circuit property

has_circuit: bool

Whether this netlist element has a defined circuit it belongs to.

Tries to access self.circuit and returns whether the call was successful. Can be used instead of a try-except clause around the call to NetlistElement.circuit.

locked property

locked: bool

True if this NetlistElement instance is locked (i.e. it is currently structurally unchangeable), False if it is mutable.

Can be changed via NetlistElement.change_mutability(bool).

Immutability is used to prevent accidental changes to the design.

is_placeholder_instance property

is_placeholder_instance: bool

A placeholder represents an element that does not have a specific path.

True if this NetlistElement instance represents a placeholder, False otherwise.

can_carry_signal property

can_carry_signal: bool

Whether this exact object is able to receive, pass or hold signal values.

True for ports (as they drive or receive values) and wires (as they pass the signals from driver to load ports) as well as their respective segments. False for instances and modules.

connections property

connections: Dict[str, Dict[int, WireSegmentPath]]

A dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port. Elements with no connection (i.e. the path is None) are excluded. In case these are needed, use Instance.get_connections() instead.

Example

{ 'port1': {1: WireSegmentPath('path/to/element1'), 2: WireSegmentPath('path/to/element2')}, 'port2': {1: WireSegmentPath('path/to/element3')} }

connection_str_paths property

connection_str_paths: Dict[str, Dict[int, str]]

Returns a dictionary mapping port names to their corresponding connection paths as strings.

The keys are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are the raw string paths.

Example

{ 'port1': {0: 'path.to.element1', 1: 'path.to.element2'}, 'port2': {0: 'path.to.element3'} }

ports property

A dictionary mapping port names to their corresponding Port objects.

The keys of the dictionary are the names of the ports. The values are Port objects representing the ports.

Returns:

input_ports property

input_ports: Tuple[Port[Instance], ...]

Returns a tuple of input ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as inputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the input ports.

output_ports property

output_ports: Tuple[Port[Instance], ...]

Returns a tuple of output ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as outputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the output ports.

has_unconnected_port_segments property

has_unconnected_port_segments: bool

Returns True if the instance has at least one unconnected port segment.

signals property

signals: Dict[str, SignalArray]

A dictionary with all signals currently present on all ports of this instance.

is_blackbox property

is_blackbox: bool

Flag indicating whether the instance represents neither a primitive element nor a module instance.

If True, this instance does not have a module definition, and is also not a basic component (i.e. a primitive gate instance) from the internal gate library, such as a gate or flip-flop.

a_width property

a_width: PositiveInt

Width of the gate's A port.

b_width property

b_width: PositiveInt

Width of the gate's B port.

is_sequential property

is_sequential: bool

Whether instances of this gate are considered sequential gates.

False for combinational gates, such as AND gates or arithmetic gates. True for flip-flops and latches.

output_port property

output_port: Port[Instance]

The output port of the gate.

data_width property

data_width: int

The data width of this instance.

Defaults to the data width of the output port. Can be overwritten in extended classes.

In contrast to self.width, which is used for the creation and initialization, this property is linked to the data width of the output port. This property is useful when the data width of the output port can be changed.

input_port property

input_port: Port[Instance]

The input port of the gate.

clk_polarity property writable

clk_polarity: Signal

Which clock edge activates the flip-flop. Default is Signal.HIGH, i.e. rising edge.

clk_port property

clk_port: Port[Instance]

The clock port of the gate.

has_en property

has_en: bool

Whether this DFF instance has an EN (enable) port.

has_rst property

has_rst: bool

Whether this DFF instance has an RST (reset) port.

scan_ff_equivalent property

scan_ff_equivalent: Type[ScanDFF]

Returns the Scan-FF type equivalent for normal FF and the FF type equivalent for Scan-FF.

rst_polarity property writable

rst_polarity: Signal

Which reset level resets the flip-flop. Default is Signal.HIGH: the flipflop is in reset, if the reset signal is HIGH.

rst_val_int property writable

rst_val_int: int

Reset value of the flip-flop as integer. Default is 0.

rst_port property

rst_port: Port[Instance]

The reset port of the gate.

rst_val property

rst_val: SignalArray

The value of the flipflop during and after reset. Default is Signal.LOW, i.e. the initial flipflop state is 0 by default.

in_reset property

in_reset: bool

True if the gate is currently in reset, False otherwise.

en_polarity property writable

en_polarity: Signal

Which EN-signal level enables writing on the data storage. Default is Signal.HIGH.

en_port property

en_port: Port[Instance]

The enable port of the gate.

en_signal property

en_signal: Signal

The enable signal of the gate.

change_mutability

change_mutability(is_now_locked: bool, recursive: bool = False) -> Self

Change the mutability status of this instance and optionally its ports.

This method allows setting whether this instance can be modified or not. If recursive is set to True, it also applies the same mutability status to all ports of this instance.

Parameters:

  • is_now_locked

    (bool) –

    The new mutability status for this instance.

  • recursive

    (bool, default: False ) –

    Whether to apply the change recursively to its ports. Defaults to False.

evaluate

evaluate() -> None

Evaluates the gate's output signal.

This method is called when the gate's input signals change, and it updates the gate's output signal accordingly.

all_connections

all_connections(
    include_unconnected: bool,
) -> Dict[str, Dict[int, WireSegmentPath]]

Returns a dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port.

Parameters:

  • include_unconnected

    (bool) –

    Whether to include unconnected ports in the result.

Returns:

connect

connect(
    port_name: str,
    ws_path: Optional[WireSegmentPath],
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add connections to the specified port of this instance.

This method can establish multiple connections if a range of indices is provided.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection(s) should be established.

  • ws_path

    (Optional[WireSegmentPath]) –

    The path of the wire segment that will be connected to this port. If None, the associated port (segment) remains unconnected.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

Raises:

  • ObjectLockedError

    If this instance is currently locked, and no connection can be made.

disconnect

disconnect(port_name: str, index: Optional[int] = None) -> None

Remove an existing connection from a specified port of this instance.

This method disconnects the wire segment at the given index within the specified port_name.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be removed.

  • index

    (Optional[int], default: None ) –

    The bit index within the port for this disconnection. Defaults to None, which completely disconnects the port.

Raises:

get_connection

get_connection(
    port_name: str, index: Optional[NonNegativeInt] = None
) -> Union[WireSegmentPath, Dict[int, WireSegmentPath], None]

Retrieve the connection path associated with a specified port and bit index.

If index is provided, this method returns the wire segment path connected to that specific bit within the port. Otherwise, it returns all connections for the given port as a dictionary mapping indices to WireSegmentPaths.

Parameters:

  • port_name

    (str) –

    The name of the port for which to retrieve the connection(s).

  • index

    (Optional[NonNegativeInt], default: None ) –

    The bit index within the port. Defaults to None.

Returns:

modify_connection

modify_connection(
    port_name: str, ws_path: WireSegmentPath, index: NonNegativeInt = 0
) -> None

Modify an existing connection within a specified port of this instance.

This method updates the wire segment path at the given index within the specified port_name. If the index does not exist yet, it is newly added, changing the width of the port.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be modified.

  • ws_path

    (WireSegmentPath) –

    The new wire segment path for this connection.

  • index

    (NonNegativeInt, default: 0 ) –

    The bit index within the port. Defaults to 0.

connect_modify

connect_modify(
    port_name: str,
    ws_path: WireSegmentPath,
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add a new connection or modify an existing one within the specified port of this instance.

If the connection already exists at the given index and port_name, it will be modified. Otherwise, a new connection is added.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be established or updated.

  • ws_path

    (WireSegmentPath) –

    The path of the wire segment that will be connected to this port.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

tie_port

tie_port(name: str, index: NonNegativeInt, sig_value: LogicLevel) -> None

Set a constant signal value for the specified port and bit index.

If the specified port does not exist, an error message is logged and the function returns False. Otherwise, the method tries to set the constant signal value for that port and returns True if successful.

Does not work for instance output ports, as they are always driven by their parent instances.

Parameters:

  • name

    (str) –

    The name of the port.

  • index

    (NonNegativeInt) –

    The bit index within the port.

  • sig_value

    (LogicLevel) –

    The constant signal value to be set ('0', '1', or 'Z').

Raises:

  • ObjectNotFoundError

    If no such port or port segment exists.

  • AlreadyConnectedError

    (raised by: PortSegment.tie_signal) If this segment is belongs to a load port and is already connected to a wire, from which it receives its value.

  • InvalidDirectionError

    (raised by: PortSegment.tie_signal) If this port segment belongs to an instance output port, which is driven by the instance inputs and the instance's internal logic.

  • InvalidSignalError

    (raised by: PortSegment.tie_signal) If an invalid value is provided.

has_tied_ports

has_tied_ports() -> bool

Checks the ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any ports of this instance are tied to constant values. False otherwise, i.e. all ports are connected to wires.

has_tied_inputs

has_tied_inputs() -> bool

Checks the input ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any input ports of this instance are tied to constant values. False otherwise, i.e. all input ports are connected to wires.

has_tied_outputs

has_tied_outputs() -> bool

Checks the output ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any output ports of this instance are tied to constant values. False otherwise, i.e. all output ports are connected to wires.

update_signedness

update_signedness(port_name: str) -> None

Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

Parameters:

  • port_name

    (str) –

    The name of the port, of which the signedness value is retrieved.

split

split() -> Dict[NonNegativeInt, Self]

Performs a bit-wise split on this instance.

If this instance supports splitting and has a data width of n bit, this method splits this instance into n 1-bit instances. This works for instances, where each output bit depends only on the corresponding input bit(s), e.g. an AND gate or a D-Flipflop.

Returns:

  • Dict[NonNegativeInt, Self]

    Dict[int, Instance]: An n-bit large dictionary, where each key conforms to a bit of the original instance, and each value is an 1-bit instance representing the corresponding "slice" of the original instance.

Raises:

  • SplittingUnsupportedError

    If this instance does not support splitting. Happens for any gate or instance whose behavior depends on the whole bus, and splitting would make it lose its meaning.

p2v

p2v(
    port: ANY_PORT,
    exclude_indices: Optional[List[int]] = None,
    include_indices: Optional[List[int]] = None,
) -> str

Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a Port object and converts them to their corresponding Verilog signal structure (p2v -> Port to Verilog signal syntax). For each segment of the port, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port is set to a constant, the corresponding constant wire segment placeholder is used instead. Port segments can be excluded from the conversion by providing a list of indices to the exclude_indices parameter, indicating which segments should be excluded from the conversion (e.g. segments that are known to be unconnected). Vice versa, only a certain subset of the port's segments may be converted to Verilog syntax, if include_indices is a given list of port indices. All indices not present in the list will be excluded from the conversion.

Parameters:

  • port

    (Port) –

    The Port object to convert.

  • exclude_indices

    (List[int], default: None ) –

    A list of indices to exclude from the conversion. Defaults to None.

  • include_indices

    (List[int], default: None ) –

    A list of indices (i.e. port slices) to include only for the conversion. Defaults to None.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

  • ObjectNotFoundError

    If the wire connected to a certain port segment could not be found.

  • UnsupportedOperationError

    If both exclude_indices and include_indices are specified. Only one of both may be given when calling this method.

ps2v

Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a PortSegment dictionary and converts them to their corresponding Verilog signal structure (ps2v -> PortSegment to Verilog signal syntax). For each segment, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port segment is set to a constant, the corresponding constant wire segment placeholder is used instead.

Parameters:

  • ps_dict

    (Dict[int, PortSegment]) –

    The PortSegment dictionary to convert. Each key (int) conforms to the index of the associated PortSegment object.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

set

set(
    port_name: str,
    new_signal: SignalOrLogicLevel,
    idx: Union[int, List[int]] = 0,
) -> None

Sets the signal on a port.

Parameters:

  • port_name

    (str) –

    The name of the port to set the signal on.

  • new_signal

    (Signal) –

    The new signal value.

  • idx

    (Union[int, List[int]], default: 0 ) –

    The index (or indices) to apply the given signal to. Can either be an integer (single index to set) or an iterable of integers (e.g. a list of indices). For every integer of the iterable the signal value of the corresponding port index is set to the given new_signal. Defaults to 0.

Example

from netlist_carpentry.utils.gate_factory import and_gate module = Module(name='m') a = module.create_port('a', 'input', width=6) instance = and_gate(module, 'inst', A=a)

This sets the value of bit 0 of port A to HIGH

instance.set('A', 1, 0) instance.ports['A'].signal_str 'xxxxx1'

This sets the value of bits 1, 3 and 5 of port A to LOW, leaving the other bits as they already are.

instance.set('A', 0, [1, 3, 5]) instance.ports['A'].signal_str '0x0x01'

set_clk

set_clk(new_signal: SignalOrLogicLevel) -> None

Sets the clock signal.

Parameters:

  • new_signal

    (Signal) –

    The new clock signal value.

get_scanff

get_scanff() -> ScanDFF

Creates and returns a scan-DFF version of this DFF, copying all parameters of this DFF.

No connections are copied however, and the instance initially does not belong to any module.

set_en

set_en(new_signal: SignalOrLogicLevel) -> None

Sets the enable signal.

Parameters:

  • new_signal

    (Signal) –

    The new enable signal value.

SDFFE

Bases: EnMixin, SDFF

Synchronously resettable DFF with enable port, where the reset signal takes precedence over the enable signal.

Methods:

  • change_mutability

    Change the mutability status of this instance and optionally its ports.

  • evaluate

    Evaluates the gate's output signal.

  • all_connections

    Returns a dictionary mapping port names to their corresponding connection paths.

  • connect

    Add connections to the specified port of this instance.

  • disconnect

    Remove an existing connection from a specified port of this instance.

  • get_connection

    Retrieve the connection path associated with a specified port and bit index.

  • modify_connection

    Modify an existing connection within a specified port of this instance.

  • connect_modify

    Add a new connection or modify an existing one within the specified port of this instance.

  • tie_port

    Set a constant signal value for the specified port and bit index.

  • has_tied_ports

    Checks the ports of this instance whether any are tied to constant values.

  • has_tied_inputs

    Checks the input ports of this instance whether any are tied to constant values.

  • has_tied_outputs

    Checks the output ports of this instance whether any are tied to constant values.

  • update_signedness

    Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

  • split

    Performs a bit-wise split on this instance.

  • p2v

    Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

  • ps2v

    Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

  • set

    Sets the signal on a port.

  • set_clk

    Sets the clock signal.

  • get_scanff

    Creates and returns a scan-DFF version of this DFF, copying all parameters of this DFF.

  • set_en

    Sets the enable signal.

Attributes:

name instance-attribute

name: str

The name of the element.

!!! Do not modify this variable after instantiating it. Use NetlistElement.set_name() instead. Modifying this variable might lead to inconsistencies later on.

metadata class-attribute instance-attribute

Metadata of a netlist element.

Can be user-defined, or e. g. by Yosys (such as src for the HDL source). Is also grouped by categories, i.e. all metadata from Yosys can be accessed via Module.metadata["yosys"], or via Module.metadata.yosys, which both return a dictionary of all metadata. Read the documentation of MetaDataMixin for more information.

path property

Returns the InstancePath of the netlist element.

The InstancePath object is constructed using the element's type and its raw hierarchical path.

Returns:

  • InstancePath ( InstancePath ) –

    The hierarchical path of the netlist element.

type property

type: EType

The type of the element, which is an instance.

hierarchy_level property

hierarchy_level: int

The level of hierarchy of the element in the design.

The hierarchy level is the number of separators in the element's raw path. For example, a top-level instance has a hierarchy level of 0, while a direct submodule instance has a hierarchy level of 1.

Returns:

  • int ( int ) –

    The hierarchy level of the element.

has_parent property

has_parent: bool

Whether this object has a parent.

circuit property

circuit: 'Circuit'

The circuit object to which this netlist element belongs to.

  • For a module, returns the circuit to which the module belongs.
  • For any other netlist element, recursively returns the circuit of the parent, which ultimately leads to a module, to which the netlist element belongs.

Raises:

  • ParentNotFoundError

    If a parent cannot be resolved somewhere in the hierarchical chain.

  • ObjectNotFoundError

    If for a module no circuit is set.

has_circuit property

has_circuit: bool

Whether this netlist element has a defined circuit it belongs to.

Tries to access self.circuit and returns whether the call was successful. Can be used instead of a try-except clause around the call to NetlistElement.circuit.

locked property

locked: bool

True if this NetlistElement instance is locked (i.e. it is currently structurally unchangeable), False if it is mutable.

Can be changed via NetlistElement.change_mutability(bool).

Immutability is used to prevent accidental changes to the design.

is_placeholder_instance property

is_placeholder_instance: bool

A placeholder represents an element that does not have a specific path.

True if this NetlistElement instance represents a placeholder, False otherwise.

can_carry_signal property

can_carry_signal: bool

Whether this exact object is able to receive, pass or hold signal values.

True for ports (as they drive or receive values) and wires (as they pass the signals from driver to load ports) as well as their respective segments. False for instances and modules.

connections property

connections: Dict[str, Dict[int, WireSegmentPath]]

A dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port. Elements with no connection (i.e. the path is None) are excluded. In case these are needed, use Instance.get_connections() instead.

Example

{ 'port1': {1: WireSegmentPath('path/to/element1'), 2: WireSegmentPath('path/to/element2')}, 'port2': {1: WireSegmentPath('path/to/element3')} }

connection_str_paths property

connection_str_paths: Dict[str, Dict[int, str]]

Returns a dictionary mapping port names to their corresponding connection paths as strings.

The keys are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are the raw string paths.

Example

{ 'port1': {0: 'path.to.element1', 1: 'path.to.element2'}, 'port2': {0: 'path.to.element3'} }

ports property

A dictionary mapping port names to their corresponding Port objects.

The keys of the dictionary are the names of the ports. The values are Port objects representing the ports.

Returns:

input_ports property

input_ports: Tuple[Port[Instance], ...]

Returns a tuple of input ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as inputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the input ports.

output_ports property

output_ports: Tuple[Port[Instance], ...]

Returns a tuple of output ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as outputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the output ports.

has_unconnected_port_segments property

has_unconnected_port_segments: bool

Returns True if the instance has at least one unconnected port segment.

signals property

signals: Dict[str, SignalArray]

A dictionary with all signals currently present on all ports of this instance.

is_blackbox property

is_blackbox: bool

Flag indicating whether the instance represents neither a primitive element nor a module instance.

If True, this instance does not have a module definition, and is also not a basic component (i.e. a primitive gate instance) from the internal gate library, such as a gate or flip-flop.

a_width property

a_width: PositiveInt

Width of the gate's A port.

b_width property

b_width: PositiveInt

Width of the gate's B port.

is_sequential property

is_sequential: bool

Whether instances of this gate are considered sequential gates.

False for combinational gates, such as AND gates or arithmetic gates. True for flip-flops and latches.

output_port property

output_port: Port[Instance]

The output port of the gate.

data_width property

data_width: int

The data width of this instance.

Defaults to the data width of the output port. Can be overwritten in extended classes.

In contrast to self.width, which is used for the creation and initialization, this property is linked to the data width of the output port. This property is useful when the data width of the output port can be changed.

input_port property

input_port: Port[Instance]

The input port of the gate.

clk_polarity property writable

clk_polarity: Signal

Which clock edge activates the flip-flop. Default is Signal.HIGH, i.e. rising edge.

clk_port property

clk_port: Port[Instance]

The clock port of the gate.

has_en property

has_en: bool

Whether this DFF instance has an EN (enable) port.

has_rst property

has_rst: bool

Whether this DFF instance has an RST (reset) port.

scan_ff_equivalent property

scan_ff_equivalent: Type[ScanDFF]

Returns the Scan-FF type equivalent for normal FF and the FF type equivalent for Scan-FF.

rst_polarity property writable

rst_polarity: Signal

Which reset level resets the flip-flop. Default is Signal.HIGH: the flipflop is in reset, if the reset signal is HIGH.

rst_val_int property writable

rst_val_int: int

Reset value of the flip-flop as integer. Default is 0.

rst_port property

rst_port: Port[Instance]

The reset port of the gate.

rst_val property

rst_val: SignalArray

The value of the flipflop during and after reset. Default is Signal.LOW, i.e. the initial flipflop state is 0 by default.

in_reset property

in_reset: bool

True if the gate is currently in reset, False otherwise.

en_polarity property writable

en_polarity: Signal

Which EN-signal level enables writing on the data storage. Default is Signal.HIGH.

en_port property

en_port: Port[Instance]

The enable port of the gate.

en_signal property

en_signal: Signal

The enable signal of the gate.

change_mutability

change_mutability(is_now_locked: bool, recursive: bool = False) -> Self

Change the mutability status of this instance and optionally its ports.

This method allows setting whether this instance can be modified or not. If recursive is set to True, it also applies the same mutability status to all ports of this instance.

Parameters:

  • is_now_locked

    (bool) –

    The new mutability status for this instance.

  • recursive

    (bool, default: False ) –

    Whether to apply the change recursively to its ports. Defaults to False.

evaluate

evaluate() -> None

Evaluates the gate's output signal.

This method is called when the gate's input signals change, and it updates the gate's output signal accordingly.

all_connections

all_connections(
    include_unconnected: bool,
) -> Dict[str, Dict[int, WireSegmentPath]]

Returns a dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port.

Parameters:

  • include_unconnected

    (bool) –

    Whether to include unconnected ports in the result.

Returns:

connect

connect(
    port_name: str,
    ws_path: Optional[WireSegmentPath],
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add connections to the specified port of this instance.

This method can establish multiple connections if a range of indices is provided.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection(s) should be established.

  • ws_path

    (Optional[WireSegmentPath]) –

    The path of the wire segment that will be connected to this port. If None, the associated port (segment) remains unconnected.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

Raises:

  • ObjectLockedError

    If this instance is currently locked, and no connection can be made.

disconnect

disconnect(port_name: str, index: Optional[int] = None) -> None

Remove an existing connection from a specified port of this instance.

This method disconnects the wire segment at the given index within the specified port_name.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be removed.

  • index

    (Optional[int], default: None ) –

    The bit index within the port for this disconnection. Defaults to None, which completely disconnects the port.

Raises:

get_connection

get_connection(
    port_name: str, index: Optional[NonNegativeInt] = None
) -> Union[WireSegmentPath, Dict[int, WireSegmentPath], None]

Retrieve the connection path associated with a specified port and bit index.

If index is provided, this method returns the wire segment path connected to that specific bit within the port. Otherwise, it returns all connections for the given port as a dictionary mapping indices to WireSegmentPaths.

Parameters:

  • port_name

    (str) –

    The name of the port for which to retrieve the connection(s).

  • index

    (Optional[NonNegativeInt], default: None ) –

    The bit index within the port. Defaults to None.

Returns:

modify_connection

modify_connection(
    port_name: str, ws_path: WireSegmentPath, index: NonNegativeInt = 0
) -> None

Modify an existing connection within a specified port of this instance.

This method updates the wire segment path at the given index within the specified port_name. If the index does not exist yet, it is newly added, changing the width of the port.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be modified.

  • ws_path

    (WireSegmentPath) –

    The new wire segment path for this connection.

  • index

    (NonNegativeInt, default: 0 ) –

    The bit index within the port. Defaults to 0.

connect_modify

connect_modify(
    port_name: str,
    ws_path: WireSegmentPath,
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add a new connection or modify an existing one within the specified port of this instance.

If the connection already exists at the given index and port_name, it will be modified. Otherwise, a new connection is added.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be established or updated.

  • ws_path

    (WireSegmentPath) –

    The path of the wire segment that will be connected to this port.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

tie_port

tie_port(name: str, index: NonNegativeInt, sig_value: LogicLevel) -> None

Set a constant signal value for the specified port and bit index.

If the specified port does not exist, an error message is logged and the function returns False. Otherwise, the method tries to set the constant signal value for that port and returns True if successful.

Does not work for instance output ports, as they are always driven by their parent instances.

Parameters:

  • name

    (str) –

    The name of the port.

  • index

    (NonNegativeInt) –

    The bit index within the port.

  • sig_value

    (LogicLevel) –

    The constant signal value to be set ('0', '1', or 'Z').

Raises:

  • ObjectNotFoundError

    If no such port or port segment exists.

  • AlreadyConnectedError

    (raised by: PortSegment.tie_signal) If this segment is belongs to a load port and is already connected to a wire, from which it receives its value.

  • InvalidDirectionError

    (raised by: PortSegment.tie_signal) If this port segment belongs to an instance output port, which is driven by the instance inputs and the instance's internal logic.

  • InvalidSignalError

    (raised by: PortSegment.tie_signal) If an invalid value is provided.

has_tied_ports

has_tied_ports() -> bool

Checks the ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any ports of this instance are tied to constant values. False otherwise, i.e. all ports are connected to wires.

has_tied_inputs

has_tied_inputs() -> bool

Checks the input ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any input ports of this instance are tied to constant values. False otherwise, i.e. all input ports are connected to wires.

has_tied_outputs

has_tied_outputs() -> bool

Checks the output ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any output ports of this instance are tied to constant values. False otherwise, i.e. all output ports are connected to wires.

update_signedness

update_signedness(port_name: str) -> None

Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

Parameters:

  • port_name

    (str) –

    The name of the port, of which the signedness value is retrieved.

split

split() -> Dict[NonNegativeInt, Self]

Performs a bit-wise split on this instance.

If this instance supports splitting and has a data width of n bit, this method splits this instance into n 1-bit instances. This works for instances, where each output bit depends only on the corresponding input bit(s), e.g. an AND gate or a D-Flipflop.

Returns:

  • Dict[NonNegativeInt, Self]

    Dict[int, Instance]: An n-bit large dictionary, where each key conforms to a bit of the original instance, and each value is an 1-bit instance representing the corresponding "slice" of the original instance.

Raises:

  • SplittingUnsupportedError

    If this instance does not support splitting. Happens for any gate or instance whose behavior depends on the whole bus, and splitting would make it lose its meaning.

p2v

p2v(
    port: ANY_PORT,
    exclude_indices: Optional[List[int]] = None,
    include_indices: Optional[List[int]] = None,
) -> str

Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a Port object and converts them to their corresponding Verilog signal structure (p2v -> Port to Verilog signal syntax). For each segment of the port, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port is set to a constant, the corresponding constant wire segment placeholder is used instead. Port segments can be excluded from the conversion by providing a list of indices to the exclude_indices parameter, indicating which segments should be excluded from the conversion (e.g. segments that are known to be unconnected). Vice versa, only a certain subset of the port's segments may be converted to Verilog syntax, if include_indices is a given list of port indices. All indices not present in the list will be excluded from the conversion.

Parameters:

  • port

    (Port) –

    The Port object to convert.

  • exclude_indices

    (List[int], default: None ) –

    A list of indices to exclude from the conversion. Defaults to None.

  • include_indices

    (List[int], default: None ) –

    A list of indices (i.e. port slices) to include only for the conversion. Defaults to None.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

  • ObjectNotFoundError

    If the wire connected to a certain port segment could not be found.

  • UnsupportedOperationError

    If both exclude_indices and include_indices are specified. Only one of both may be given when calling this method.

ps2v

Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a PortSegment dictionary and converts them to their corresponding Verilog signal structure (ps2v -> PortSegment to Verilog signal syntax). For each segment, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port segment is set to a constant, the corresponding constant wire segment placeholder is used instead.

Parameters:

  • ps_dict

    (Dict[int, PortSegment]) –

    The PortSegment dictionary to convert. Each key (int) conforms to the index of the associated PortSegment object.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

set

set(
    port_name: str,
    new_signal: SignalOrLogicLevel,
    idx: Union[int, List[int]] = 0,
) -> None

Sets the signal on a port.

Parameters:

  • port_name

    (str) –

    The name of the port to set the signal on.

  • new_signal

    (Signal) –

    The new signal value.

  • idx

    (Union[int, List[int]], default: 0 ) –

    The index (or indices) to apply the given signal to. Can either be an integer (single index to set) or an iterable of integers (e.g. a list of indices). For every integer of the iterable the signal value of the corresponding port index is set to the given new_signal. Defaults to 0.

Example

from netlist_carpentry.utils.gate_factory import and_gate module = Module(name='m') a = module.create_port('a', 'input', width=6) instance = and_gate(module, 'inst', A=a)

This sets the value of bit 0 of port A to HIGH

instance.set('A', 1, 0) instance.ports['A'].signal_str 'xxxxx1'

This sets the value of bits 1, 3 and 5 of port A to LOW, leaving the other bits as they already are.

instance.set('A', 0, [1, 3, 5]) instance.ports['A'].signal_str '0x0x01'

set_clk

set_clk(new_signal: SignalOrLogicLevel) -> None

Sets the clock signal.

Parameters:

  • new_signal

    (Signal) –

    The new clock signal value.

get_scanff

get_scanff() -> ScanDFF

Creates and returns a scan-DFF version of this DFF, copying all parameters of this DFF.

No connections are copied however, and the instance initially does not belong to any module.

set_en

set_en(new_signal: SignalOrLogicLevel) -> None

Sets the enable signal.

Parameters:

  • new_signal

    (Signal) –

    The new enable signal value.

ALDFF

Bases: LoadMixin, DFF

Asynchronously load DFF, with a load-enable (AL) and load-data (AD) port.

Methods:

  • change_mutability

    Change the mutability status of this instance and optionally its ports.

  • evaluate

    Evaluates the gate's output signal.

  • all_connections

    Returns a dictionary mapping port names to their corresponding connection paths.

  • connect

    Add connections to the specified port of this instance.

  • disconnect

    Remove an existing connection from a specified port of this instance.

  • get_connection

    Retrieve the connection path associated with a specified port and bit index.

  • modify_connection

    Modify an existing connection within a specified port of this instance.

  • connect_modify

    Add a new connection or modify an existing one within the specified port of this instance.

  • tie_port

    Set a constant signal value for the specified port and bit index.

  • has_tied_ports

    Checks the ports of this instance whether any are tied to constant values.

  • has_tied_inputs

    Checks the input ports of this instance whether any are tied to constant values.

  • has_tied_outputs

    Checks the output ports of this instance whether any are tied to constant values.

  • update_signedness

    Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

  • split

    Performs a bit-wise split on this instance.

  • p2v

    Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

  • ps2v

    Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

  • set

    Sets the signal on a port.

  • set_clk

    Sets the clock signal.

  • get_scanff

    Creates and returns a scan-DFF version of this DFF, copying all parameters of this DFF.

  • set_al

    Sets the asynchronous load enable signal.

Attributes:

  • name (str) –

    The name of the element.

  • metadata (MetadataMixin) –

    Metadata of a netlist element.

  • path (InstancePath) –

    Returns the InstancePath of the netlist element.

  • type (EType) –

    The type of the element, which is an instance.

  • hierarchy_level (int) –

    The level of hierarchy of the element in the design.

  • has_parent (bool) –

    Whether this object has a parent.

  • circuit ('Circuit') –

    The circuit object to which this netlist element belongs to.

  • has_circuit (bool) –

    Whether this netlist element has a defined circuit it belongs to.

  • locked (bool) –

    True if this NetlistElement instance is locked (i.e. it is currently structurally unchangeable), False if it is mutable.

  • is_placeholder_instance (bool) –

    A placeholder represents an element that does not have a specific path.

  • can_carry_signal (bool) –

    Whether this exact object is able to receive, pass or hold signal values.

  • connections (Dict[str, Dict[int, WireSegmentPath]]) –

    A dictionary mapping port names to their corresponding connection paths.

  • connection_str_paths (Dict[str, Dict[int, str]]) –

    Returns a dictionary mapping port names to their corresponding connection paths as strings.

  • ports (CustomDict[str, Port[Instance]]) –

    A dictionary mapping port names to their corresponding Port objects.

  • input_ports (Tuple[Port[Instance], ...]) –

    Returns a tuple of input ports associated with this instance.

  • output_ports (Tuple[Port[Instance], ...]) –

    Returns a tuple of output ports associated with this instance.

  • has_unconnected_port_segments (bool) –

    Returns True if the instance has at least one unconnected port segment.

  • signals (Dict[str, SignalArray]) –

    A dictionary with all signals currently present on all ports of this instance.

  • is_blackbox (bool) –

    Flag indicating whether the instance represents neither a primitive element nor a module instance.

  • a_width (PositiveInt) –

    Width of the gate's A port.

  • b_width (PositiveInt) –

    Width of the gate's B port.

  • is_sequential (bool) –

    Whether instances of this gate are considered sequential gates.

  • output_port (Port[Instance]) –

    The output port of the gate.

  • data_width (int) –

    The data width of this instance.

  • input_port (Port[Instance]) –

    The input port of the gate.

  • clk_polarity (Signal) –

    Which clock edge activates the flip-flop. Default is Signal.HIGH, i.e. rising edge.

  • clk_port (Port[Instance]) –

    The clock port of the gate.

  • has_en (bool) –

    Whether this DFF instance has an EN (enable) port.

  • has_rst (bool) –

    Whether this DFF instance has an RST (reset) port.

  • scan_ff_equivalent (Type[ScanDFF]) –

    Returns the Scan-FF type equivalent for normal FF and the FF type equivalent for Scan-FF.

  • load_polarity (Signal) –

    Which load level loads the load value into flip-flop. Default is Signal.HIGH: the flipflop will load, if the load signal is HIGH.

  • al_port (Port[Instance]) –

    The asynchronous load enable port of the gate, i.e. the port that toggles whether to load data into the flip-flop.

  • ad_port (Port[Instance]) –

    The asynchronous data load port of the gate, i.e. the port that holds the data to load into the flip-flop.

  • load_val (SignalArray) –

    The value of the flipflop during and after reset, retrieved from the load data port.

  • load_val_int (Optional[int]) –

    The value of the flipflop during and after reset as an integer, retrieved from the load data port.

  • in_load (bool) –

    True if the gate is currently in "load-value" mode, False otherwise.

name instance-attribute

name: str

The name of the element.

!!! Do not modify this variable after instantiating it. Use NetlistElement.set_name() instead. Modifying this variable might lead to inconsistencies later on.

metadata class-attribute instance-attribute

Metadata of a netlist element.

Can be user-defined, or e. g. by Yosys (such as src for the HDL source). Is also grouped by categories, i.e. all metadata from Yosys can be accessed via Module.metadata["yosys"], or via Module.metadata.yosys, which both return a dictionary of all metadata. Read the documentation of MetaDataMixin for more information.

path property

Returns the InstancePath of the netlist element.

The InstancePath object is constructed using the element's type and its raw hierarchical path.

Returns:

  • InstancePath ( InstancePath ) –

    The hierarchical path of the netlist element.

type property

type: EType

The type of the element, which is an instance.

hierarchy_level property

hierarchy_level: int

The level of hierarchy of the element in the design.

The hierarchy level is the number of separators in the element's raw path. For example, a top-level instance has a hierarchy level of 0, while a direct submodule instance has a hierarchy level of 1.

Returns:

  • int ( int ) –

    The hierarchy level of the element.

has_parent property

has_parent: bool

Whether this object has a parent.

circuit property

circuit: 'Circuit'

The circuit object to which this netlist element belongs to.

  • For a module, returns the circuit to which the module belongs.
  • For any other netlist element, recursively returns the circuit of the parent, which ultimately leads to a module, to which the netlist element belongs.

Raises:

  • ParentNotFoundError

    If a parent cannot be resolved somewhere in the hierarchical chain.

  • ObjectNotFoundError

    If for a module no circuit is set.

has_circuit property

has_circuit: bool

Whether this netlist element has a defined circuit it belongs to.

Tries to access self.circuit and returns whether the call was successful. Can be used instead of a try-except clause around the call to NetlistElement.circuit.

locked property

locked: bool

True if this NetlistElement instance is locked (i.e. it is currently structurally unchangeable), False if it is mutable.

Can be changed via NetlistElement.change_mutability(bool).

Immutability is used to prevent accidental changes to the design.

is_placeholder_instance property

is_placeholder_instance: bool

A placeholder represents an element that does not have a specific path.

True if this NetlistElement instance represents a placeholder, False otherwise.

can_carry_signal property

can_carry_signal: bool

Whether this exact object is able to receive, pass or hold signal values.

True for ports (as they drive or receive values) and wires (as they pass the signals from driver to load ports) as well as their respective segments. False for instances and modules.

connections property

connections: Dict[str, Dict[int, WireSegmentPath]]

A dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port. Elements with no connection (i.e. the path is None) are excluded. In case these are needed, use Instance.get_connections() instead.

Example

{ 'port1': {1: WireSegmentPath('path/to/element1'), 2: WireSegmentPath('path/to/element2')}, 'port2': {1: WireSegmentPath('path/to/element3')} }

connection_str_paths property

connection_str_paths: Dict[str, Dict[int, str]]

Returns a dictionary mapping port names to their corresponding connection paths as strings.

The keys are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are the raw string paths.

Example

{ 'port1': {0: 'path.to.element1', 1: 'path.to.element2'}, 'port2': {0: 'path.to.element3'} }

ports property

A dictionary mapping port names to their corresponding Port objects.

The keys of the dictionary are the names of the ports. The values are Port objects representing the ports.

Returns:

input_ports property

input_ports: Tuple[Port[Instance], ...]

Returns a tuple of input ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as inputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the input ports.

output_ports property

output_ports: Tuple[Port[Instance], ...]

Returns a tuple of output ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as outputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the output ports.

has_unconnected_port_segments property

has_unconnected_port_segments: bool

Returns True if the instance has at least one unconnected port segment.

signals property

signals: Dict[str, SignalArray]

A dictionary with all signals currently present on all ports of this instance.

is_blackbox property

is_blackbox: bool

Flag indicating whether the instance represents neither a primitive element nor a module instance.

If True, this instance does not have a module definition, and is also not a basic component (i.e. a primitive gate instance) from the internal gate library, such as a gate or flip-flop.

a_width property

a_width: PositiveInt

Width of the gate's A port.

b_width property

b_width: PositiveInt

Width of the gate's B port.

is_sequential property

is_sequential: bool

Whether instances of this gate are considered sequential gates.

False for combinational gates, such as AND gates or arithmetic gates. True for flip-flops and latches.

output_port property

output_port: Port[Instance]

The output port of the gate.

data_width property

data_width: int

The data width of this instance.

Defaults to the data width of the output port. Can be overwritten in extended classes.

In contrast to self.width, which is used for the creation and initialization, this property is linked to the data width of the output port. This property is useful when the data width of the output port can be changed.

input_port property

input_port: Port[Instance]

The input port of the gate.

clk_polarity property writable

clk_polarity: Signal

Which clock edge activates the flip-flop. Default is Signal.HIGH, i.e. rising edge.

clk_port property

clk_port: Port[Instance]

The clock port of the gate.

has_en property

has_en: bool

Whether this DFF instance has an EN (enable) port.

has_rst property

has_rst: bool

Whether this DFF instance has an RST (reset) port.

scan_ff_equivalent property

scan_ff_equivalent: Type[ScanDFF]

Returns the Scan-FF type equivalent for normal FF and the FF type equivalent for Scan-FF.

load_polarity property writable

load_polarity: Signal

Which load level loads the load value into flip-flop. Default is Signal.HIGH: the flipflop will load, if the load signal is HIGH.

al_port property

al_port: Port[Instance]

The asynchronous load enable port of the gate, i.e. the port that toggles whether to load data into the flip-flop.

ad_port property

ad_port: Port[Instance]

The asynchronous data load port of the gate, i.e. the port that holds the data to load into the flip-flop.

load_val property

load_val: SignalArray

The value of the flipflop during and after reset, retrieved from the load data port.

load_val_int property

load_val_int: Optional[int]

The value of the flipflop during and after reset as an integer, retrieved from the load data port.

in_load property

in_load: bool

True if the gate is currently in "load-value" mode, False otherwise.

change_mutability

change_mutability(is_now_locked: bool, recursive: bool = False) -> Self

Change the mutability status of this instance and optionally its ports.

This method allows setting whether this instance can be modified or not. If recursive is set to True, it also applies the same mutability status to all ports of this instance.

Parameters:

  • is_now_locked

    (bool) –

    The new mutability status for this instance.

  • recursive

    (bool, default: False ) –

    Whether to apply the change recursively to its ports. Defaults to False.

evaluate

evaluate() -> None

Evaluates the gate's output signal.

This method is called when the gate's input signals change, and it updates the gate's output signal accordingly.

all_connections

all_connections(
    include_unconnected: bool,
) -> Dict[str, Dict[int, WireSegmentPath]]

Returns a dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port.

Parameters:

  • include_unconnected

    (bool) –

    Whether to include unconnected ports in the result.

Returns:

connect

connect(
    port_name: str,
    ws_path: Optional[WireSegmentPath],
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add connections to the specified port of this instance.

This method can establish multiple connections if a range of indices is provided.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection(s) should be established.

  • ws_path

    (Optional[WireSegmentPath]) –

    The path of the wire segment that will be connected to this port. If None, the associated port (segment) remains unconnected.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

Raises:

  • ObjectLockedError

    If this instance is currently locked, and no connection can be made.

disconnect

disconnect(port_name: str, index: Optional[int] = None) -> None

Remove an existing connection from a specified port of this instance.

This method disconnects the wire segment at the given index within the specified port_name.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be removed.

  • index

    (Optional[int], default: None ) –

    The bit index within the port for this disconnection. Defaults to None, which completely disconnects the port.

Raises:

get_connection

get_connection(
    port_name: str, index: Optional[NonNegativeInt] = None
) -> Union[WireSegmentPath, Dict[int, WireSegmentPath], None]

Retrieve the connection path associated with a specified port and bit index.

If index is provided, this method returns the wire segment path connected to that specific bit within the port. Otherwise, it returns all connections for the given port as a dictionary mapping indices to WireSegmentPaths.

Parameters:

  • port_name

    (str) –

    The name of the port for which to retrieve the connection(s).

  • index

    (Optional[NonNegativeInt], default: None ) –

    The bit index within the port. Defaults to None.

Returns:

modify_connection

modify_connection(
    port_name: str, ws_path: WireSegmentPath, index: NonNegativeInt = 0
) -> None

Modify an existing connection within a specified port of this instance.

This method updates the wire segment path at the given index within the specified port_name. If the index does not exist yet, it is newly added, changing the width of the port.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be modified.

  • ws_path

    (WireSegmentPath) –

    The new wire segment path for this connection.

  • index

    (NonNegativeInt, default: 0 ) –

    The bit index within the port. Defaults to 0.

connect_modify

connect_modify(
    port_name: str,
    ws_path: WireSegmentPath,
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add a new connection or modify an existing one within the specified port of this instance.

If the connection already exists at the given index and port_name, it will be modified. Otherwise, a new connection is added.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be established or updated.

  • ws_path

    (WireSegmentPath) –

    The path of the wire segment that will be connected to this port.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

tie_port

tie_port(name: str, index: NonNegativeInt, sig_value: LogicLevel) -> None

Set a constant signal value for the specified port and bit index.

If the specified port does not exist, an error message is logged and the function returns False. Otherwise, the method tries to set the constant signal value for that port and returns True if successful.

Does not work for instance output ports, as they are always driven by their parent instances.

Parameters:

  • name

    (str) –

    The name of the port.

  • index

    (NonNegativeInt) –

    The bit index within the port.

  • sig_value

    (LogicLevel) –

    The constant signal value to be set ('0', '1', or 'Z').

Raises:

  • ObjectNotFoundError

    If no such port or port segment exists.

  • AlreadyConnectedError

    (raised by: PortSegment.tie_signal) If this segment is belongs to a load port and is already connected to a wire, from which it receives its value.

  • InvalidDirectionError

    (raised by: PortSegment.tie_signal) If this port segment belongs to an instance output port, which is driven by the instance inputs and the instance's internal logic.

  • InvalidSignalError

    (raised by: PortSegment.tie_signal) If an invalid value is provided.

has_tied_ports

has_tied_ports() -> bool

Checks the ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any ports of this instance are tied to constant values. False otherwise, i.e. all ports are connected to wires.

has_tied_inputs

has_tied_inputs() -> bool

Checks the input ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any input ports of this instance are tied to constant values. False otherwise, i.e. all input ports are connected to wires.

has_tied_outputs

has_tied_outputs() -> bool

Checks the output ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any output ports of this instance are tied to constant values. False otherwise, i.e. all output ports are connected to wires.

update_signedness

update_signedness(port_name: str) -> None

Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

Parameters:

  • port_name

    (str) –

    The name of the port, of which the signedness value is retrieved.

split

split() -> Dict[NonNegativeInt, Self]

Performs a bit-wise split on this instance.

If this instance supports splitting and has a data width of n bit, this method splits this instance into n 1-bit instances. This works for instances, where each output bit depends only on the corresponding input bit(s), e.g. an AND gate or a D-Flipflop.

Returns:

  • Dict[NonNegativeInt, Self]

    Dict[int, Instance]: An n-bit large dictionary, where each key conforms to a bit of the original instance, and each value is an 1-bit instance representing the corresponding "slice" of the original instance.

Raises:

  • SplittingUnsupportedError

    If this instance does not support splitting. Happens for any gate or instance whose behavior depends on the whole bus, and splitting would make it lose its meaning.

p2v

p2v(
    port: ANY_PORT,
    exclude_indices: Optional[List[int]] = None,
    include_indices: Optional[List[int]] = None,
) -> str

Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a Port object and converts them to their corresponding Verilog signal structure (p2v -> Port to Verilog signal syntax). For each segment of the port, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port is set to a constant, the corresponding constant wire segment placeholder is used instead. Port segments can be excluded from the conversion by providing a list of indices to the exclude_indices parameter, indicating which segments should be excluded from the conversion (e.g. segments that are known to be unconnected). Vice versa, only a certain subset of the port's segments may be converted to Verilog syntax, if include_indices is a given list of port indices. All indices not present in the list will be excluded from the conversion.

Parameters:

  • port

    (Port) –

    The Port object to convert.

  • exclude_indices

    (List[int], default: None ) –

    A list of indices to exclude from the conversion. Defaults to None.

  • include_indices

    (List[int], default: None ) –

    A list of indices (i.e. port slices) to include only for the conversion. Defaults to None.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

  • ObjectNotFoundError

    If the wire connected to a certain port segment could not be found.

  • UnsupportedOperationError

    If both exclude_indices and include_indices are specified. Only one of both may be given when calling this method.

ps2v

Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a PortSegment dictionary and converts them to their corresponding Verilog signal structure (ps2v -> PortSegment to Verilog signal syntax). For each segment, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port segment is set to a constant, the corresponding constant wire segment placeholder is used instead.

Parameters:

  • ps_dict

    (Dict[int, PortSegment]) –

    The PortSegment dictionary to convert. Each key (int) conforms to the index of the associated PortSegment object.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

set

set(
    port_name: str,
    new_signal: SignalOrLogicLevel,
    idx: Union[int, List[int]] = 0,
) -> None

Sets the signal on a port.

Parameters:

  • port_name

    (str) –

    The name of the port to set the signal on.

  • new_signal

    (Signal) –

    The new signal value.

  • idx

    (Union[int, List[int]], default: 0 ) –

    The index (or indices) to apply the given signal to. Can either be an integer (single index to set) or an iterable of integers (e.g. a list of indices). For every integer of the iterable the signal value of the corresponding port index is set to the given new_signal. Defaults to 0.

Example

from netlist_carpentry.utils.gate_factory import and_gate module = Module(name='m') a = module.create_port('a', 'input', width=6) instance = and_gate(module, 'inst', A=a)

This sets the value of bit 0 of port A to HIGH

instance.set('A', 1, 0) instance.ports['A'].signal_str 'xxxxx1'

This sets the value of bits 1, 3 and 5 of port A to LOW, leaving the other bits as they already are.

instance.set('A', 0, [1, 3, 5]) instance.ports['A'].signal_str '0x0x01'

set_clk

set_clk(new_signal: SignalOrLogicLevel) -> None

Sets the clock signal.

Parameters:

  • new_signal

    (Signal) –

    The new clock signal value.

get_scanff

get_scanff() -> ScanDFF

Creates and returns a scan-DFF version of this DFF, copying all parameters of this DFF.

No connections are copied however, and the instance initially does not belong to any module.

set_al

set_al(new_signal: SignalOrLogicLevel) -> None

Sets the asynchronous load enable signal.

Parameters:

  • new_signal

    (Signal) –

    The new asynchronous load enable signal value.

ALDFFE

Bases: EnMixin, ALDFF

Asynchronously load DFF, with a load-enable (AL) and load-data (AD) port and an additional enable port for the default case.

Methods:

  • change_mutability

    Change the mutability status of this instance and optionally its ports.

  • evaluate

    Evaluates the gate's output signal.

  • all_connections

    Returns a dictionary mapping port names to their corresponding connection paths.

  • connect

    Add connections to the specified port of this instance.

  • disconnect

    Remove an existing connection from a specified port of this instance.

  • get_connection

    Retrieve the connection path associated with a specified port and bit index.

  • modify_connection

    Modify an existing connection within a specified port of this instance.

  • connect_modify

    Add a new connection or modify an existing one within the specified port of this instance.

  • tie_port

    Set a constant signal value for the specified port and bit index.

  • has_tied_ports

    Checks the ports of this instance whether any are tied to constant values.

  • has_tied_inputs

    Checks the input ports of this instance whether any are tied to constant values.

  • has_tied_outputs

    Checks the output ports of this instance whether any are tied to constant values.

  • update_signedness

    Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

  • split

    Performs a bit-wise split on this instance.

  • p2v

    Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

  • ps2v

    Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

  • set

    Sets the signal on a port.

  • set_clk

    Sets the clock signal.

  • get_scanff

    Creates and returns a scan-DFF version of this DFF, copying all parameters of this DFF.

  • set_al

    Sets the asynchronous load enable signal.

  • set_en

    Sets the enable signal.

Attributes:

name instance-attribute

name: str

The name of the element.

!!! Do not modify this variable after instantiating it. Use NetlistElement.set_name() instead. Modifying this variable might lead to inconsistencies later on.

metadata class-attribute instance-attribute

Metadata of a netlist element.

Can be user-defined, or e. g. by Yosys (such as src for the HDL source). Is also grouped by categories, i.e. all metadata from Yosys can be accessed via Module.metadata["yosys"], or via Module.metadata.yosys, which both return a dictionary of all metadata. Read the documentation of MetaDataMixin for more information.

path property

Returns the InstancePath of the netlist element.

The InstancePath object is constructed using the element's type and its raw hierarchical path.

Returns:

  • InstancePath ( InstancePath ) –

    The hierarchical path of the netlist element.

type property

type: EType

The type of the element, which is an instance.

hierarchy_level property

hierarchy_level: int

The level of hierarchy of the element in the design.

The hierarchy level is the number of separators in the element's raw path. For example, a top-level instance has a hierarchy level of 0, while a direct submodule instance has a hierarchy level of 1.

Returns:

  • int ( int ) –

    The hierarchy level of the element.

has_parent property

has_parent: bool

Whether this object has a parent.

circuit property

circuit: 'Circuit'

The circuit object to which this netlist element belongs to.

  • For a module, returns the circuit to which the module belongs.
  • For any other netlist element, recursively returns the circuit of the parent, which ultimately leads to a module, to which the netlist element belongs.

Raises:

  • ParentNotFoundError

    If a parent cannot be resolved somewhere in the hierarchical chain.

  • ObjectNotFoundError

    If for a module no circuit is set.

has_circuit property

has_circuit: bool

Whether this netlist element has a defined circuit it belongs to.

Tries to access self.circuit and returns whether the call was successful. Can be used instead of a try-except clause around the call to NetlistElement.circuit.

locked property

locked: bool

True if this NetlistElement instance is locked (i.e. it is currently structurally unchangeable), False if it is mutable.

Can be changed via NetlistElement.change_mutability(bool).

Immutability is used to prevent accidental changes to the design.

is_placeholder_instance property

is_placeholder_instance: bool

A placeholder represents an element that does not have a specific path.

True if this NetlistElement instance represents a placeholder, False otherwise.

can_carry_signal property

can_carry_signal: bool

Whether this exact object is able to receive, pass or hold signal values.

True for ports (as they drive or receive values) and wires (as they pass the signals from driver to load ports) as well as their respective segments. False for instances and modules.

connections property

connections: Dict[str, Dict[int, WireSegmentPath]]

A dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port. Elements with no connection (i.e. the path is None) are excluded. In case these are needed, use Instance.get_connections() instead.

Example

{ 'port1': {1: WireSegmentPath('path/to/element1'), 2: WireSegmentPath('path/to/element2')}, 'port2': {1: WireSegmentPath('path/to/element3')} }

connection_str_paths property

connection_str_paths: Dict[str, Dict[int, str]]

Returns a dictionary mapping port names to their corresponding connection paths as strings.

The keys are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are the raw string paths.

Example

{ 'port1': {0: 'path.to.element1', 1: 'path.to.element2'}, 'port2': {0: 'path.to.element3'} }

ports property

A dictionary mapping port names to their corresponding Port objects.

The keys of the dictionary are the names of the ports. The values are Port objects representing the ports.

Returns:

input_ports property

input_ports: Tuple[Port[Instance], ...]

Returns a tuple of input ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as inputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the input ports.

output_ports property

output_ports: Tuple[Port[Instance], ...]

Returns a tuple of output ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as outputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the output ports.

has_unconnected_port_segments property

has_unconnected_port_segments: bool

Returns True if the instance has at least one unconnected port segment.

signals property

signals: Dict[str, SignalArray]

A dictionary with all signals currently present on all ports of this instance.

is_blackbox property

is_blackbox: bool

Flag indicating whether the instance represents neither a primitive element nor a module instance.

If True, this instance does not have a module definition, and is also not a basic component (i.e. a primitive gate instance) from the internal gate library, such as a gate or flip-flop.

a_width property

a_width: PositiveInt

Width of the gate's A port.

b_width property

b_width: PositiveInt

Width of the gate's B port.

is_sequential property

is_sequential: bool

Whether instances of this gate are considered sequential gates.

False for combinational gates, such as AND gates or arithmetic gates. True for flip-flops and latches.

output_port property

output_port: Port[Instance]

The output port of the gate.

data_width property

data_width: int

The data width of this instance.

Defaults to the data width of the output port. Can be overwritten in extended classes.

In contrast to self.width, which is used for the creation and initialization, this property is linked to the data width of the output port. This property is useful when the data width of the output port can be changed.

input_port property

input_port: Port[Instance]

The input port of the gate.

clk_polarity property writable

clk_polarity: Signal

Which clock edge activates the flip-flop. Default is Signal.HIGH, i.e. rising edge.

clk_port property

clk_port: Port[Instance]

The clock port of the gate.

has_en property

has_en: bool

Whether this DFF instance has an EN (enable) port.

has_rst property

has_rst: bool

Whether this DFF instance has an RST (reset) port.

scan_ff_equivalent property

scan_ff_equivalent: Type[ScanDFF]

Returns the Scan-FF type equivalent for normal FF and the FF type equivalent for Scan-FF.

load_polarity property writable

load_polarity: Signal

Which load level loads the load value into flip-flop. Default is Signal.HIGH: the flipflop will load, if the load signal is HIGH.

al_port property

al_port: Port[Instance]

The asynchronous load enable port of the gate, i.e. the port that toggles whether to load data into the flip-flop.

ad_port property

ad_port: Port[Instance]

The asynchronous data load port of the gate, i.e. the port that holds the data to load into the flip-flop.

load_val property

load_val: SignalArray

The value of the flipflop during and after reset, retrieved from the load data port.

load_val_int property

load_val_int: Optional[int]

The value of the flipflop during and after reset as an integer, retrieved from the load data port.

in_load property

in_load: bool

True if the gate is currently in "load-value" mode, False otherwise.

en_polarity property writable

en_polarity: Signal

Which EN-signal level enables writing on the data storage. Default is Signal.HIGH.

en_port property

en_port: Port[Instance]

The enable port of the gate.

en_signal property

en_signal: Signal

The enable signal of the gate.

change_mutability

change_mutability(is_now_locked: bool, recursive: bool = False) -> Self

Change the mutability status of this instance and optionally its ports.

This method allows setting whether this instance can be modified or not. If recursive is set to True, it also applies the same mutability status to all ports of this instance.

Parameters:

  • is_now_locked

    (bool) –

    The new mutability status for this instance.

  • recursive

    (bool, default: False ) –

    Whether to apply the change recursively to its ports. Defaults to False.

evaluate

evaluate() -> None

Evaluates the gate's output signal.

This method is called when the gate's input signals change, and it updates the gate's output signal accordingly.

all_connections

all_connections(
    include_unconnected: bool,
) -> Dict[str, Dict[int, WireSegmentPath]]

Returns a dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port.

Parameters:

  • include_unconnected

    (bool) –

    Whether to include unconnected ports in the result.

Returns:

connect

connect(
    port_name: str,
    ws_path: Optional[WireSegmentPath],
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add connections to the specified port of this instance.

This method can establish multiple connections if a range of indices is provided.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection(s) should be established.

  • ws_path

    (Optional[WireSegmentPath]) –

    The path of the wire segment that will be connected to this port. If None, the associated port (segment) remains unconnected.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

Raises:

  • ObjectLockedError

    If this instance is currently locked, and no connection can be made.

disconnect

disconnect(port_name: str, index: Optional[int] = None) -> None

Remove an existing connection from a specified port of this instance.

This method disconnects the wire segment at the given index within the specified port_name.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be removed.

  • index

    (Optional[int], default: None ) –

    The bit index within the port for this disconnection. Defaults to None, which completely disconnects the port.

Raises:

get_connection

get_connection(
    port_name: str, index: Optional[NonNegativeInt] = None
) -> Union[WireSegmentPath, Dict[int, WireSegmentPath], None]

Retrieve the connection path associated with a specified port and bit index.

If index is provided, this method returns the wire segment path connected to that specific bit within the port. Otherwise, it returns all connections for the given port as a dictionary mapping indices to WireSegmentPaths.

Parameters:

  • port_name

    (str) –

    The name of the port for which to retrieve the connection(s).

  • index

    (Optional[NonNegativeInt], default: None ) –

    The bit index within the port. Defaults to None.

Returns:

modify_connection

modify_connection(
    port_name: str, ws_path: WireSegmentPath, index: NonNegativeInt = 0
) -> None

Modify an existing connection within a specified port of this instance.

This method updates the wire segment path at the given index within the specified port_name. If the index does not exist yet, it is newly added, changing the width of the port.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be modified.

  • ws_path

    (WireSegmentPath) –

    The new wire segment path for this connection.

  • index

    (NonNegativeInt, default: 0 ) –

    The bit index within the port. Defaults to 0.

connect_modify

connect_modify(
    port_name: str,
    ws_path: WireSegmentPath,
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add a new connection or modify an existing one within the specified port of this instance.

If the connection already exists at the given index and port_name, it will be modified. Otherwise, a new connection is added.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be established or updated.

  • ws_path

    (WireSegmentPath) –

    The path of the wire segment that will be connected to this port.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

tie_port

tie_port(name: str, index: NonNegativeInt, sig_value: LogicLevel) -> None

Set a constant signal value for the specified port and bit index.

If the specified port does not exist, an error message is logged and the function returns False. Otherwise, the method tries to set the constant signal value for that port and returns True if successful.

Does not work for instance output ports, as they are always driven by their parent instances.

Parameters:

  • name

    (str) –

    The name of the port.

  • index

    (NonNegativeInt) –

    The bit index within the port.

  • sig_value

    (LogicLevel) –

    The constant signal value to be set ('0', '1', or 'Z').

Raises:

  • ObjectNotFoundError

    If no such port or port segment exists.

  • AlreadyConnectedError

    (raised by: PortSegment.tie_signal) If this segment is belongs to a load port and is already connected to a wire, from which it receives its value.

  • InvalidDirectionError

    (raised by: PortSegment.tie_signal) If this port segment belongs to an instance output port, which is driven by the instance inputs and the instance's internal logic.

  • InvalidSignalError

    (raised by: PortSegment.tie_signal) If an invalid value is provided.

has_tied_ports

has_tied_ports() -> bool

Checks the ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any ports of this instance are tied to constant values. False otherwise, i.e. all ports are connected to wires.

has_tied_inputs

has_tied_inputs() -> bool

Checks the input ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any input ports of this instance are tied to constant values. False otherwise, i.e. all input ports are connected to wires.

has_tied_outputs

has_tied_outputs() -> bool

Checks the output ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any output ports of this instance are tied to constant values. False otherwise, i.e. all output ports are connected to wires.

update_signedness

update_signedness(port_name: str) -> None

Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

Parameters:

  • port_name

    (str) –

    The name of the port, of which the signedness value is retrieved.

split

split() -> Dict[NonNegativeInt, Self]

Performs a bit-wise split on this instance.

If this instance supports splitting and has a data width of n bit, this method splits this instance into n 1-bit instances. This works for instances, where each output bit depends only on the corresponding input bit(s), e.g. an AND gate or a D-Flipflop.

Returns:

  • Dict[NonNegativeInt, Self]

    Dict[int, Instance]: An n-bit large dictionary, where each key conforms to a bit of the original instance, and each value is an 1-bit instance representing the corresponding "slice" of the original instance.

Raises:

  • SplittingUnsupportedError

    If this instance does not support splitting. Happens for any gate or instance whose behavior depends on the whole bus, and splitting would make it lose its meaning.

p2v

p2v(
    port: ANY_PORT,
    exclude_indices: Optional[List[int]] = None,
    include_indices: Optional[List[int]] = None,
) -> str

Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a Port object and converts them to their corresponding Verilog signal structure (p2v -> Port to Verilog signal syntax). For each segment of the port, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port is set to a constant, the corresponding constant wire segment placeholder is used instead. Port segments can be excluded from the conversion by providing a list of indices to the exclude_indices parameter, indicating which segments should be excluded from the conversion (e.g. segments that are known to be unconnected). Vice versa, only a certain subset of the port's segments may be converted to Verilog syntax, if include_indices is a given list of port indices. All indices not present in the list will be excluded from the conversion.

Parameters:

  • port

    (Port) –

    The Port object to convert.

  • exclude_indices

    (List[int], default: None ) –

    A list of indices to exclude from the conversion. Defaults to None.

  • include_indices

    (List[int], default: None ) –

    A list of indices (i.e. port slices) to include only for the conversion. Defaults to None.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

  • ObjectNotFoundError

    If the wire connected to a certain port segment could not be found.

  • UnsupportedOperationError

    If both exclude_indices and include_indices are specified. Only one of both may be given when calling this method.

ps2v

Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a PortSegment dictionary and converts them to their corresponding Verilog signal structure (ps2v -> PortSegment to Verilog signal syntax). For each segment, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port segment is set to a constant, the corresponding constant wire segment placeholder is used instead.

Parameters:

  • ps_dict

    (Dict[int, PortSegment]) –

    The PortSegment dictionary to convert. Each key (int) conforms to the index of the associated PortSegment object.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

set

set(
    port_name: str,
    new_signal: SignalOrLogicLevel,
    idx: Union[int, List[int]] = 0,
) -> None

Sets the signal on a port.

Parameters:

  • port_name

    (str) –

    The name of the port to set the signal on.

  • new_signal

    (Signal) –

    The new signal value.

  • idx

    (Union[int, List[int]], default: 0 ) –

    The index (or indices) to apply the given signal to. Can either be an integer (single index to set) or an iterable of integers (e.g. a list of indices). For every integer of the iterable the signal value of the corresponding port index is set to the given new_signal. Defaults to 0.

Example

from netlist_carpentry.utils.gate_factory import and_gate module = Module(name='m') a = module.create_port('a', 'input', width=6) instance = and_gate(module, 'inst', A=a)

This sets the value of bit 0 of port A to HIGH

instance.set('A', 1, 0) instance.ports['A'].signal_str 'xxxxx1'

This sets the value of bits 1, 3 and 5 of port A to LOW, leaving the other bits as they already are.

instance.set('A', 0, [1, 3, 5]) instance.ports['A'].signal_str '0x0x01'

set_clk

set_clk(new_signal: SignalOrLogicLevel) -> None

Sets the clock signal.

Parameters:

  • new_signal

    (Signal) –

    The new clock signal value.

get_scanff

get_scanff() -> ScanDFF

Creates and returns a scan-DFF version of this DFF, copying all parameters of this DFF.

No connections are copied however, and the instance initially does not belong to any module.

set_al

set_al(new_signal: SignalOrLogicLevel) -> None

Sets the asynchronous load enable signal.

Parameters:

  • new_signal

    (Signal) –

    The new asynchronous load enable signal value.

set_en

set_en(new_signal: SignalOrLogicLevel) -> None

Sets the enable signal.

Parameters:

  • new_signal

    (Signal) –

    The new enable signal value.

DFFSRE

Bases: EnMixin, DFFSR

Methods:

  • set_en

    Sets the enable signal.

  • change_mutability

    Change the mutability status of this instance and optionally its ports.

  • evaluate

    Evaluates the gate's output signal.

  • all_connections

    Returns a dictionary mapping port names to their corresponding connection paths.

  • connect

    Add connections to the specified port of this instance.

  • disconnect

    Remove an existing connection from a specified port of this instance.

  • get_connection

    Retrieve the connection path associated with a specified port and bit index.

  • modify_connection

    Modify an existing connection within a specified port of this instance.

  • connect_modify

    Add a new connection or modify an existing one within the specified port of this instance.

  • tie_port

    Set a constant signal value for the specified port and bit index.

  • has_tied_ports

    Checks the ports of this instance whether any are tied to constant values.

  • has_tied_inputs

    Checks the input ports of this instance whether any are tied to constant values.

  • has_tied_outputs

    Checks the output ports of this instance whether any are tied to constant values.

  • update_signedness

    Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

  • split

    Performs a bit-wise split on this instance.

  • p2v

    Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

  • ps2v

    Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

  • set

    Sets the signal on a port.

  • set_clk

    Sets the clock signal.

  • get_scanff

    Creates and returns a scan-DFF version of this DFF, copying all parameters of this DFF.

  • set_clr

    Sets the clear signal.

  • set_set

    Sets the set signal.

Attributes:

name instance-attribute

name: str

The name of the element.

!!! Do not modify this variable after instantiating it. Use NetlistElement.set_name() instead. Modifying this variable might lead to inconsistencies later on.

metadata class-attribute instance-attribute

Metadata of a netlist element.

Can be user-defined, or e. g. by Yosys (such as src for the HDL source). Is also grouped by categories, i.e. all metadata from Yosys can be accessed via Module.metadata["yosys"], or via Module.metadata.yosys, which both return a dictionary of all metadata. Read the documentation of MetaDataMixin for more information.

path property

Returns the InstancePath of the netlist element.

The InstancePath object is constructed using the element's type and its raw hierarchical path.

Returns:

  • InstancePath ( InstancePath ) –

    The hierarchical path of the netlist element.

type property

type: EType

The type of the element, which is an instance.

hierarchy_level property

hierarchy_level: int

The level of hierarchy of the element in the design.

The hierarchy level is the number of separators in the element's raw path. For example, a top-level instance has a hierarchy level of 0, while a direct submodule instance has a hierarchy level of 1.

Returns:

  • int ( int ) –

    The hierarchy level of the element.

has_parent property

has_parent: bool

Whether this object has a parent.

circuit property

circuit: 'Circuit'

The circuit object to which this netlist element belongs to.

  • For a module, returns the circuit to which the module belongs.
  • For any other netlist element, recursively returns the circuit of the parent, which ultimately leads to a module, to which the netlist element belongs.

Raises:

  • ParentNotFoundError

    If a parent cannot be resolved somewhere in the hierarchical chain.

  • ObjectNotFoundError

    If for a module no circuit is set.

has_circuit property

has_circuit: bool

Whether this netlist element has a defined circuit it belongs to.

Tries to access self.circuit and returns whether the call was successful. Can be used instead of a try-except clause around the call to NetlistElement.circuit.

locked property

locked: bool

True if this NetlistElement instance is locked (i.e. it is currently structurally unchangeable), False if it is mutable.

Can be changed via NetlistElement.change_mutability(bool).

Immutability is used to prevent accidental changes to the design.

is_placeholder_instance property

is_placeholder_instance: bool

A placeholder represents an element that does not have a specific path.

True if this NetlistElement instance represents a placeholder, False otherwise.

can_carry_signal property

can_carry_signal: bool

Whether this exact object is able to receive, pass or hold signal values.

True for ports (as they drive or receive values) and wires (as they pass the signals from driver to load ports) as well as their respective segments. False for instances and modules.

connections property

connections: Dict[str, Dict[int, WireSegmentPath]]

A dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port. Elements with no connection (i.e. the path is None) are excluded. In case these are needed, use Instance.get_connections() instead.

Example

{ 'port1': {1: WireSegmentPath('path/to/element1'), 2: WireSegmentPath('path/to/element2')}, 'port2': {1: WireSegmentPath('path/to/element3')} }

connection_str_paths property

connection_str_paths: Dict[str, Dict[int, str]]

Returns a dictionary mapping port names to their corresponding connection paths as strings.

The keys are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are the raw string paths.

Example

{ 'port1': {0: 'path.to.element1', 1: 'path.to.element2'}, 'port2': {0: 'path.to.element3'} }

ports property

A dictionary mapping port names to their corresponding Port objects.

The keys of the dictionary are the names of the ports. The values are Port objects representing the ports.

Returns:

input_ports property

input_ports: Tuple[Port[Instance], ...]

Returns a tuple of input ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as inputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the input ports.

output_ports property

output_ports: Tuple[Port[Instance], ...]

Returns a tuple of output ports associated with this instance.

This property filters the ports based on their direction, returning only those that are marked as outputs.

Returns:

  • Tuple[Port[Instance], ...]

    A tuple of Port objects representing the output ports.

has_unconnected_port_segments property

has_unconnected_port_segments: bool

Returns True if the instance has at least one unconnected port segment.

signals property

signals: Dict[str, SignalArray]

A dictionary with all signals currently present on all ports of this instance.

is_blackbox property

is_blackbox: bool

Flag indicating whether the instance represents neither a primitive element nor a module instance.

If True, this instance does not have a module definition, and is also not a basic component (i.e. a primitive gate instance) from the internal gate library, such as a gate or flip-flop.

a_width property

a_width: PositiveInt

Width of the gate's A port.

b_width property

b_width: PositiveInt

Width of the gate's B port.

is_sequential property

is_sequential: bool

Whether instances of this gate are considered sequential gates.

False for combinational gates, such as AND gates or arithmetic gates. True for flip-flops and latches.

output_port property

output_port: Port[Instance]

The output port of the gate.

data_width property

data_width: int

The data width of this instance.

Defaults to the data width of the output port. Can be overwritten in extended classes.

In contrast to self.width, which is used for the creation and initialization, this property is linked to the data width of the output port. This property is useful when the data width of the output port can be changed.

input_port property

input_port: Port[Instance]

The input port of the gate.

clk_polarity property writable

clk_polarity: Signal

Which clock edge activates the flip-flop. Default is Signal.HIGH, i.e. rising edge.

clk_port property

clk_port: Port[Instance]

The clock port of the gate.

has_en property

has_en: bool

Whether this DFF instance has an EN (enable) port.

has_rst property

has_rst: bool

Whether this DFF instance has an RST (reset) port.

scan_ff_equivalent property

scan_ff_equivalent: Type[ScanDFF]

Returns the Scan-FF type equivalent for normal FF and the FF type equivalent for Scan-FF.

clr_polarity property writable

clr_polarity: Signal

Which clear level clears the flip-flop. Default is Signal.HIGH: the flipflop goes to 0, if the clear signal is HIGH.

clr_port property

clr_port: Port[Instance]

The clear port of the gate.

set_polarity property writable

set_polarity: Signal

Which set level sets the flip-flop. Default is Signal.HIGH: the flipflop goes to 1, if the set signal is HIGH.

set_port property

set_port: Port[Instance]

The set port of the gate.

en_polarity property writable

en_polarity: Signal

Which EN-signal level enables writing on the data storage. Default is Signal.HIGH.

en_port property

en_port: Port[Instance]

The enable port of the gate.

en_signal property

en_signal: Signal

The enable signal of the gate.

set_en

set_en(new_signal: SignalOrLogicLevel, idx: Union[int, List[int]] = 0) -> None

Sets the enable signal.

Parameters:

  • new_signal

    (Signal) –

    The new enable signal value.

  • idx

    (Union[int, List[int]], default: 0 ) –

    The index (or indices) to apply the given signal to. Can either be an integer (single index to set) or an iterable of integers (e.g. a list of indices). For every integer of the iterable the signal value of the corresponding port index is set to the given new_signal. Defaults to 0.

change_mutability

change_mutability(is_now_locked: bool, recursive: bool = False) -> Self

Change the mutability status of this instance and optionally its ports.

This method allows setting whether this instance can be modified or not. If recursive is set to True, it also applies the same mutability status to all ports of this instance.

Parameters:

  • is_now_locked

    (bool) –

    The new mutability status for this instance.

  • recursive

    (bool, default: False ) –

    Whether to apply the change recursively to its ports. Defaults to False.

evaluate

evaluate() -> None

Evaluates the gate's output signal.

This method is called when the gate's input signals change, and it updates the gate's output signal accordingly.

all_connections

all_connections(
    include_unconnected: bool,
) -> Dict[str, Dict[int, WireSegmentPath]]

Returns a dictionary mapping port names to their corresponding connection paths.

The keys of the outer dictionary are the names of the ports. The values are dictionaries where the keys are the port bit numbers and the values are WireSegmentPath objects. The element paths are the paths of the wires connected to the corresponding bits of the port.

Parameters:

  • include_unconnected

    (bool) –

    Whether to include unconnected ports in the result.

Returns:

connect

connect(
    port_name: str,
    ws_path: Optional[WireSegmentPath],
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add connections to the specified port of this instance.

This method can establish multiple connections if a range of indices is provided.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection(s) should be established.

  • ws_path

    (Optional[WireSegmentPath]) –

    The path of the wire segment that will be connected to this port. If None, the associated port (segment) remains unconnected.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

Raises:

  • ObjectLockedError

    If this instance is currently locked, and no connection can be made.

disconnect

disconnect(port_name: str, index: Optional[int] = None) -> None

Remove an existing connection from a specified port of this instance.

This method disconnects the wire segment at the given index within the specified port_name.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be removed.

  • index

    (Optional[int], default: None ) –

    The bit index within the port for this disconnection. Defaults to None, which completely disconnects the port.

Raises:

get_connection

get_connection(
    port_name: str, index: Optional[NonNegativeInt] = None
) -> Union[WireSegmentPath, Dict[int, WireSegmentPath], None]

Retrieve the connection path associated with a specified port and bit index.

If index is provided, this method returns the wire segment path connected to that specific bit within the port. Otherwise, it returns all connections for the given port as a dictionary mapping indices to WireSegmentPaths.

Parameters:

  • port_name

    (str) –

    The name of the port for which to retrieve the connection(s).

  • index

    (Optional[NonNegativeInt], default: None ) –

    The bit index within the port. Defaults to None.

Returns:

modify_connection

modify_connection(
    port_name: str, ws_path: WireSegmentPath, index: NonNegativeInt = 0
) -> None

Modify an existing connection within a specified port of this instance.

This method updates the wire segment path at the given index within the specified port_name. If the index does not exist yet, it is newly added, changing the width of the port.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be modified.

  • ws_path

    (WireSegmentPath) –

    The new wire segment path for this connection.

  • index

    (NonNegativeInt, default: 0 ) –

    The bit index within the port. Defaults to 0.

connect_modify

connect_modify(
    port_name: str,
    ws_path: WireSegmentPath,
    direction: Direction = UNKNOWN,
    index: NonNegativeInt = 0,
    width: PositiveInt = 1,
) -> None

Add a new connection or modify an existing one within the specified port of this instance.

If the connection already exists at the given index and port_name, it will be modified. Otherwise, a new connection is added.

Parameters:

  • port_name

    (str) –

    The name of the port where the connection should be established or updated.

  • ws_path

    (WireSegmentPath) –

    The path of the wire segment that will be connected to this port.

  • direction

    (Direction, default: UNKNOWN ) –

    The direction of the port. Defaults to Direction.UNKNOWN.

  • index

    (NonNegativeInt, default: 0 ) –

    The starting bit index within the port for these connections. Defaults to 0.

  • width

    (PositiveInt, default: 1 ) –

    The number of consecutive bits in the port that should be connected. Defaults to 1.

tie_port

tie_port(name: str, index: NonNegativeInt, sig_value: LogicLevel) -> None

Set a constant signal value for the specified port and bit index.

If the specified port does not exist, an error message is logged and the function returns False. Otherwise, the method tries to set the constant signal value for that port and returns True if successful.

Does not work for instance output ports, as they are always driven by their parent instances.

Parameters:

  • name

    (str) –

    The name of the port.

  • index

    (NonNegativeInt) –

    The bit index within the port.

  • sig_value

    (LogicLevel) –

    The constant signal value to be set ('0', '1', or 'Z').

Raises:

  • ObjectNotFoundError

    If no such port or port segment exists.

  • AlreadyConnectedError

    (raised by: PortSegment.tie_signal) If this segment is belongs to a load port and is already connected to a wire, from which it receives its value.

  • InvalidDirectionError

    (raised by: PortSegment.tie_signal) If this port segment belongs to an instance output port, which is driven by the instance inputs and the instance's internal logic.

  • InvalidSignalError

    (raised by: PortSegment.tie_signal) If an invalid value is provided.

has_tied_ports

has_tied_ports() -> bool

Checks the ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any ports of this instance are tied to constant values. False otherwise, i.e. all ports are connected to wires.

has_tied_inputs

has_tied_inputs() -> bool

Checks the input ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any input ports of this instance are tied to constant values. False otherwise, i.e. all input ports are connected to wires.

has_tied_outputs

has_tied_outputs() -> bool

Checks the output ports of this instance whether any are tied to constant values.

Instance ports can be tied to a constant value for several reasons, but if all input or all output ports are tied, the instance is rendered useless.

Returns:

  • bool ( bool ) –

    True if any output ports of this instance are tied to constant values. False otherwise, i.e. all output ports are connected to wires.

update_signedness

update_signedness(port_name: str) -> None

Retrieves the signedness of the given port and updates it in this gate instance's parameter dictionary.

Parameters:

  • port_name

    (str) –

    The name of the port, of which the signedness value is retrieved.

split

split() -> Dict[NonNegativeInt, Self]

Performs a bit-wise split on this instance.

If this instance supports splitting and has a data width of n bit, this method splits this instance into n 1-bit instances. This works for instances, where each output bit depends only on the corresponding input bit(s), e.g. an AND gate or a D-Flipflop.

Returns:

  • Dict[NonNegativeInt, Self]

    Dict[int, Instance]: An n-bit large dictionary, where each key conforms to a bit of the original instance, and each value is an 1-bit instance representing the corresponding "slice" of the original instance.

Raises:

  • SplittingUnsupportedError

    If this instance does not support splitting. Happens for any gate or instance whose behavior depends on the whole bus, and splitting would make it lose its meaning.

p2v

p2v(
    port: ANY_PORT,
    exclude_indices: Optional[List[int]] = None,
    include_indices: Optional[List[int]] = None,
) -> str

Converts a Port object to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a Port object and converts them to their corresponding Verilog signal structure (p2v -> Port to Verilog signal syntax). For each segment of the port, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port is set to a constant, the corresponding constant wire segment placeholder is used instead. Port segments can be excluded from the conversion by providing a list of indices to the exclude_indices parameter, indicating which segments should be excluded from the conversion (e.g. segments that are known to be unconnected). Vice versa, only a certain subset of the port's segments may be converted to Verilog syntax, if include_indices is a given list of port indices. All indices not present in the list will be excluded from the conversion.

Parameters:

  • port

    (Port) –

    The Port object to convert.

  • exclude_indices

    (List[int], default: None ) –

    A list of indices to exclude from the conversion. Defaults to None.

  • include_indices

    (List[int], default: None ) –

    A list of indices (i.e. port slices) to include only for the conversion. Defaults to None.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

  • ObjectNotFoundError

    If the wire connected to a certain port segment could not be found.

  • UnsupportedOperationError

    If both exclude_indices and include_indices are specified. Only one of both may be given when calling this method.

ps2v

Converts a PortSegment dictionary to its corresponding Verilog structure by using the connected wire segments.

This method takes the connected wire segments of a PortSegment dictionary and converts them to their corresponding Verilog signal structure (ps2v -> PortSegment to Verilog signal syntax). For each segment, it checks whether a corresponding connected wire segment exists in the corresponding module. If the port segment is set to a constant, the corresponding constant wire segment placeholder is used instead.

Parameters:

  • ps_dict

    (Dict[int, PortSegment]) –

    The PortSegment dictionary to convert. Each key (int) conforms to the index of the associated PortSegment object.

Returns:

  • str ( str ) –

    The Verilog signal structure as a string, e.g. some_wire[3:0] or {w, 2'b01}.

Raises:

set

set(
    port_name: str,
    new_signal: SignalOrLogicLevel,
    idx: Union[int, List[int]] = 0,
) -> None

Sets the signal on a port.

Parameters:

  • port_name

    (str) –

    The name of the port to set the signal on.

  • new_signal

    (Signal) –

    The new signal value.

  • idx

    (Union[int, List[int]], default: 0 ) –

    The index (or indices) to apply the given signal to. Can either be an integer (single index to set) or an iterable of integers (e.g. a list of indices). For every integer of the iterable the signal value of the corresponding port index is set to the given new_signal. Defaults to 0.

Example

from netlist_carpentry.utils.gate_factory import and_gate module = Module(name='m') a = module.create_port('a', 'input', width=6) instance = and_gate(module, 'inst', A=a)

This sets the value of bit 0 of port A to HIGH

instance.set('A', 1, 0) instance.ports['A'].signal_str 'xxxxx1'

This sets the value of bits 1, 3 and 5 of port A to LOW, leaving the other bits as they already are.

instance.set('A', 0, [1, 3, 5]) instance.ports['A'].signal_str '0x0x01'

set_clk

set_clk(new_signal: SignalOrLogicLevel) -> None

Sets the clock signal.

Parameters:

  • new_signal

    (Signal) –

    The new clock signal value.

get_scanff

get_scanff() -> ScanDFF

Creates and returns a scan-DFF version of this DFF, copying all parameters of this DFF.

No connections are copied however, and the instance initially does not belong to any module.

set_clr

set_clr(new_signal: SignalOrLogicLevel, idx: Union[int, List[int]]) -> None

Sets the clear signal.

Parameters:

  • new_signal

    (Signal) –

    The new clear signal value.

  • idx

    (Union[int, List[int]]) –

    The index (or indices) to apply the given signal to. Can either be an integer (single index to set) or an iterable of integers (e.g. a list of indices). For every integer of the iterable the signal value of the corresponding port index is set to the given new_signal. Defaults to 0.

set_set

set_set(new_signal: SignalOrLogicLevel, idx: Union[int, List[int]]) -> None

Sets the set signal.

Parameters:

  • new_signal

    (Signal) –

    The new set signal value.

  • idx

    (Union[int, List[int]]) –

    The index (or indices) to apply the given signal to. Can either be an integer (single index to set) or an iterable of integers (e.g. a list of indices). For every integer of the iterable the signal value of the corresponding port index is set to the given new_signal. Defaults to 0.

get

Retrieves the class of a primitive gate based on its instance type.

This function is needed to find the correct class for a primitive gate given its instance type. It searches for a class in the gate_lib module, whose instance type matches the given instance_type string.

Parameters:

  • instance_type

    (str) –

    The instance type of the primitive gate.

Returns:

  • Union[type[PrimitiveGate], None]

    Union[type[_PrimitiveGate], None]: The class of the primitive gate or None if not found.