### Install Dependencies using apt-get Source: https://github.com/synthesys-lab/assassyn/blob/master/README.md Installs necessary system dependencies for Assassyn on Ubuntu-based systems by parsing the Dockerfile and extracting apt-get install commands. It filters out empty lines and formats the output for the shell. ```sh sudo apt-get update sudo apt-get install -y $( awk '/apt-get install/,/apt-get clean/' Dockerfile | sed '1d;$d; s/[\\\[:space:]]*$//; s/^[[:space:]]*//' | grep -v '^$' | tr '\n' ' ' ) ``` -------------------------------- ### Initialize Git Submodules Source: https://github.com/synthesys-lab/assassyn/blob/master/docs/vm/docker.md This command recursively initializes and updates all git submodules for the project. It's a prerequisite before proceeding with other setup steps. ```shell git submodule update --init --recursive ``` -------------------------------- ### Verify Assassyn Installation with Python Source: https://github.com/synthesys-lab/assassyn/blob/master/README.md Verifies the Assassyn installation by attempting to import the 'assassyn' module in Python. An exit code of 0 indicates a successful import. ```python python -c 'import assassyn' ``` -------------------------------- ### Initialize Build Environment in Docker Container Source: https://github.com/synthesys-lab/assassyn/blob/master/docs/vm/docker.md Executes the initialization script './init.sh' inside the running Assassyn Docker container. This is typically done for the first-time setup of the build environment. ```shell docker exec -it ./init.sh ``` -------------------------------- ### Set Up Environment Variables and Build Project Source: https://github.com/synthesys-lab/assassyn/blob/master/README.md Sets up the necessary environment variables using the 'setup.sh' script and then builds all project components using 'make build-all'. This is a crucial step after installing dependencies. ```sh source setup.sh # Set up environment variables make build-all # Build all components ``` -------------------------------- ### Assassyn Backend Usage Example (Python) Source: https://github.com/synthesys-lab/assassyn/blob/master/python/assassyn/backend.md Demonstrates the typical usage pattern of the Assassyn backend module. It shows how to create a system using 'SysBuilder', configure elaboration parameters using 'backend.config', and prepare for the elaboration process. ```python import assassyn.backend as backend # Create system sys = assassyn.SysBuilder("my_system") # ... build system ... # Configure elaboration config = backend.config( simulator=True, verilog=True, sim_threshold=1000, idle_threshold=500 ) ``` -------------------------------- ### Multi-Port Array Write Example (Python) Source: https://github.com/synthesys-lab/assassyn/blob/master/python/assassyn/codegen/simulator/port_mapper.md A Python example demonstrating how multiple modules can write to the same array, with the port mapper assigning unique ports to each writer. ```python array = RegArray(Int(32), 10) class ModuleA(Module): def build(self, arr: Array): (arr & self)[0] <= value_a # Gets port 0 class ModuleB(Module): def build(self, arr: Array): (arr & self)[1] <= value_b # Gets port 1 class ModuleC(Module): def build(self, arr: Array): (arr & self)[2] <= value_c # Gets port 2 ``` -------------------------------- ### Initialize NamingManager Source: https://github.com/synthesys-lab/assassyn/blob/master/python/assassyn/builder/naming_manager.md Initializes a new NamingManager instance, creating a fresh TypeOrientedNamer and a per-instance module-name cache. This is the starting point for using the naming system. ```python def __init__(self): # Creates a fresh TypeOrientedNamer and per-instance module-name cache. ``` -------------------------------- ### Build Docker Image for Assassyn Source: https://github.com/synthesys-lab/assassyn/blob/master/docs/vm/docker.md Builds the Docker image for the Assassyn project using the provided Dockerfile. The image is tagged as 'assassyn:latest'. Ensure you are in the root directory of the source tree. ```docker docker build -t assassyn:latest . ``` -------------------------------- ### Build Multi-Stage Pipeline with Assassyn Source: https://context7.com/synthesys-lab/assassyn/llms.txt Demonstrates constructing a multi-stage pipeline with asynchronous communication, memory access, and conditional logic using Assassyn. This example defines three modules: DataGenerator, DataProcessor, and ResultConsumer, and orchestrates their interaction to process data through the pipeline. ```python from assassyn.frontend import * from assassyn.backend import elaborate from assassyn import utils # Stage 1: Data Generator class DataGenerator(Module): def __init__(self): super().__init__(ports={}) self.counter = RegArray(UInt(32), 1) @module.combinational def build(self, processor): cnt = self.counter (cnt & self)[0] <= cnt[0] + UInt(32)(1) with Condition(cnt[0] < UInt(32)(100)): processor.async_called(data=cnt[0]) # Stage 2: Data Processor with Memory class DataProcessor(Module): def __init__(self): super().__init__( ports={'data': Port(UInt(32))} ) @module.combinational def build(self, consumer): data = self.pop_all_ports(True) # Process data doubled = data << UInt(32)(1) # Multiply by 2 # Store in local SRAM sram = SRAM(32, 256, None) we = Bits(1)(1) re = Bits(1)(0) addr = data[0:7].bitcast(Bits(8)) sram.build(we, re, addr, doubled.bitcast(Bits(32))) # Forward to consumer consumer.data_in.push(doubled) log("Processor: input={}, output={}", data, doubled) return sram # Stage 3: Result Consumer class ResultConsumer(Module): def __init__(self): super().__init__( ports={'data_in': Port(UInt(32))} ) self.accumulator = RegArray(UInt(64), 1) @module.combinational def build(self): data = self.pop_all_ports(True) accum = self.accumulator new_sum = accum[0] + data.zext(UInt(64)) (accum & self)[0] <= new_sum log("Consumer: received={}, total={}", data, new_sum) # Build and run def main(): sys = SysBuilder('pipeline_demo') with sys: consumer = ResultConsumer() consumer.build() processor = DataProcessor() processor.build(consumer) generator = DataGenerator() generator.build(processor) print(sys) # Print IR sim_path, _ = elaborate( sys, sim_threshold=200, idle_threshold=50 ) output = utils.run_simulator(sim_path) print(output) if __name__ == '__main__': main() ``` -------------------------------- ### CreditCounter Usage Example (Python) Source: https://github.com/synthesys-lab/assassyn/blob/master/python/assassyn/ip/credit.md Demonstrates how to instantiate and use the CreditCounter module within a pipeline. It shows setting up the counter and calling its build method with delta and pop_ready signals to manage credits. ```python from assassyn.frontend import * from assassyn.ip.credit import CreditCounter # Create counter with 8-bit width counter = CreditCounter(width=8, debug=False) # In a Module's build method: delta = UInt(8)(2) # Add 2 credits pop_ready = UInt(1)(1) # Pop 1 credit delta_ready, pop_valid = counter.build(delta, pop_ready) # delta_ready indicates if counter can accept more credits # pop_valid indicates if counter has credits to pop ``` -------------------------------- ### Makefile Patch Target Example Source: https://github.com/synthesys-lab/assassyn/blob/master/docs/design/internal/build-system.md Defines a patch target for a specific component, ensuring patches are applied only once by checking for a marker file. This pattern is used to manage component-specific patches within the build system. ```makefile patch-: 3rd-party//.patch-applied ``` -------------------------------- ### Example: Register Array with Initializer (Python) Source: https://github.com/synthesys-lab/assassyn/blob/master/python/assassyn/ir/array.md Shows how to declare a single-element register array initialized to 0 using the RegArray function. This is useful for creating counters or single-value registers. ```python # Array with initial values counter = RegArray(Int(32), 1, initializer=[0]) # Single-element counter initialized to 0 ``` -------------------------------- ### Elaborate Simulator Implementation (Python) Source: https://github.com/synthesys-lab/assassyn/blob/master/python/assassyn/codegen/simulator/elaborate.md Internal implementation of the simulator elaboration function, mirroring its Rust counterpart. It handles directory setup, discovers external FFI modules, configures the project by writing the manifest and rustfmt.toml, orchestrates Rust source file generation, and returns the manifest path. ```python def elaborate_impl(sys, config): """Internal implementation of the elaborate function. This matches the Rust function in src/backend/simulator/elaborate.rs """ # Implementation details omitted for brevity ``` -------------------------------- ### Run Assassyn Docker Container Source: https://github.com/synthesys-lab/assassyn/blob/master/docs/vm/docker.md Runs the Assassyn Docker container. It mounts the current directory to '/app', sets user permissions, limits memory to 32GB, and names the container 'assassyn'. The '--rm' flag ensures the container is removed upon exit. Note that memory limits (-m) may behave differently on non-Linux systems. ```shell docker run --rm -tid -v `pwd`:/app --user $(id -u):$(id -g) \ -m 32g \ --name assassyn assassyn:latest ``` -------------------------------- ### Elaborate Verilog System Source: https://github.com/synthesys-lab/assassyn/blob/master/python/assassyn/codegen/verilog/elaborate.md The main entry point for Verilog code generation, orchestrating the complete elaboration process. It handles directory setup, external module analysis, design generation, alias discovery, testbench generation, SRAM blackbox generation, and resource file management. Dependencies include the system builder, design generation, testbench generation, external module integration, and SRAM memory models. ```python def elaborate(sys: SysBuilder, **kwargs) -> str: """Elaborate the system into Verilog. Args: sys: The system to elaborate **kwargs: Configuration options including: - verilog: The simulator to use ("Verilator", "VCS", or None) - resource_base: Path to resources - override_dump: Whether to override existing files - sim_threshold: Simulation threshold - idle_threshold: Idle threshold - random: Whether to randomize execution - fifo_depth: Default FIFO depth Returns: Path to the generated Verilog files """ # ... implementation details ... pass ``` -------------------------------- ### Check Verilator Availability (Python) Source: https://github.com/synthesys-lab/assassyn/blob/master/python/assassyn/utils/README.md Determines if Verilator is installed and accessible. It checks for the VERILATOR_ROOT environment variable and the importability of the 'pycde' package. The function returns 'verilator' if available, otherwise None. Results are cached. ```python def has_verilator() -> str | None: # Checks for Verilator availability by verifying VERILATOR_ROOT and pycde import. # Returns 'verilator' if found, None otherwise. Caches results. if VERILATOR_CACHE is not None: return VERILATOR_CACHE # ... (rest of the implementation) return 'verilator' # or None ``` -------------------------------- ### Get Simulator Binary Path Source: https://github.com/synthesys-lab/assassyn/blob/master/python/assassyn/utils/README.md Determines the path to a compiled simulator binary without building it. It parses the Cargo.toml file to find the package name and constructs the binary path, respecting the CARGO_TARGET_DIR environment variable. Requires Python 3.11+ or the 'toml' package. ```python def get_simulator_binary_path(manifest_path: str) -> str: """ Get the path to the compiled simulator binary. **Parameters:** - `manifest_path`: Path to the Cargo.toml manifest file **Returns:** - The absolute path to the compiled binary executable """ # Implementation details omitted for brevity pass ``` -------------------------------- ### Example: Basic Register Array Declaration (Python) Source: https://github.com/synthesys-lab/assassyn/blob/master/python/assassyn/ir/array.md Demonstrates the basic declaration of a register array named 'register_file' using the RegArray function. The array will store 16 elements of 32-bit unsigned integers. ```python # Basic array declaration my_array = RegArray(UInt(32), 16, name="register_file") # 16-element array of 32-bit uints ``` -------------------------------- ### Reset Port Manager in Elaborate (Python) Source: https://github.com/synthesys-lab/assassyn/blob/master/python/assassyn/codegen/simulator/port_mapper.md Example of how to reset the port manager at the start of a compilation process, ensuring a clean state for port assignments. ```python from .port_mapper import reset_port_manager reset_port_manager() ``` -------------------------------- ### Get Write Port Count - Python Source: https://github.com/synthesys-lab/assassyn/blob/master/python/assassyn/codegen/verilog/array.md A shortcut method to get the total number of write ports for a given array. ```python def write_port_count(self, array) -> int: """ Shortcut returning the total number of write ports for array. """ pass ``` -------------------------------- ### Generate Verilog Design File using Python Source: https://github.com/synthesys-lab/assassyn/blob/master/python/assassyn/codegen/verilog/design.md The `generate_design` function creates a complete Verilog design file for an Assassyn system. It handles file setup, SRAM module generation, system processing using CIRCTDumper, code output, and returns log statements. Project-specific knowledge of system builder, SRAM models, CIRCTDumper, and Verilog elaboration is required. ```python def generate_design(fname: Union[str, Path], sys: SysBuilder): """Generate a complete Verilog design file for the system.""" # ... implementation details ... ``` -------------------------------- ### Implement Port Operations (push, pop, valid, peek) Source: https://context7.com/synthesys-lab/assassyn/llms.txt Illustrates port operations for FIFO-based communication between modules. It covers pushing data, popping data, checking for data validity, and peeking at data without consuming it. Examples include explicit port operations and implicit calls. ```python from assassyn.frontend import * class Producer(Module): def __init__(self): super().__init__(ports={}) @module.combinational def build(self, consumer): cnt = RegArray(UInt(32), 1) (cnt & self)[0] <= cnt[0] + UInt(32)(1) # Explicit push to consumer's port consumer.data_in.push(cnt[0]) class Consumer(Module): def __init__(self): super().__init__( ports={'data_in': Port(UInt(32))} ) @module.combinational def build(self): # Method 1: pop_all_ports - waits for all ports, sets timing mode # True = backpressure mode (wait until valid) data = self.pop_all_ports(True) # Method 2: Explicit port operations # Check if data is available if_valid = self.data_in.valid() # Peek without consuming peeked_value = self.data_in.peek() # Pop and consume (use inside Condition) with Condition(if_valid): consumed = self.data_in.pop() log("Received: {}", consumed) class Caller(Module): def __init__(self): super().__init__(ports={}) @module.combinational def build(self, target): # async_called automatically pushes to all ports # Target module executes in the NEXT cycle target.async_called(data_in=UInt(32)(42)) # Equivalent explicit operations: # target.data_in.push(UInt(32)(42)) ``` -------------------------------- ### Get Read Port Count - Python Source: https://github.com/synthesys-lab/assassyn/blob/master/python/assassyn/codegen/verilog/array.md A shortcut method to get the total number of read ports for a given array. ```python def read_port_count(self, array) -> int: """ Shortcut returning the total number of read ports for array. """ pass ``` -------------------------------- ### Build Hardware System with SysBuilder and Elaborate Source: https://context7.com/synthesys-lab/assassyn/llms.txt Demonstrates how to use the SysBuilder class to define and construct a hardware system. It shows module instantiation, context management, and elaboration into a simulator and Verilog. Dependencies include 'assassyn.frontend', 'assassyn.backend', and 'assassyn.utils'. ```python from assassyn.frontend import * from assassyn.backend import elaborate from assassyn import utils # Create a system builder with a name sys = SysBuilder('my_system') # Use context manager to define the system with sys: # Instantiate and build modules inside the context adder = Adder() adder.build() driver = Driver() driver.build(adder) # Print the generated IR print(sys) # Elaborate to generate simulator and optionally Verilog simulator_path, verilog_path = elaborate( sys, verilog=utils.has_verilator(), # Generate Verilog if Verilator available sim_threshold=200, # Maximum simulation cycles idle_threshold=200, # Idle cycles before termination fifo_depth=4 # Default FIFO depth ) # Run the generated simulator raw_output = utils.run_simulator(simulator_path) ``` -------------------------------- ### Get Repository Path - Python Source: https://github.com/synthesys-lab/assassyn/blob/master/python/assassyn/utils/README.md Retrieves the absolute path to the assassyn repository root directory by reading the `ASSASSYN_HOME` environment variable. The result is cached globally to optimize performance. This function is essential for locating repository resources. ```python def repo_path() -> str: # ... implementation details ... pass ``` -------------------------------- ### Import Assassyn Frontend Module Source: https://github.com/synthesys-lab/assassyn/blob/master/python/assassyn/frontend.md Demonstrates the common ways to import the Assassyn frontend module for accessing its core functionality. This allows users to work with hardware description components through a unified API. ```python import assassyn.frontend as assassyn # or from assassyn import frontend ``` -------------------------------- ### Get Package Path - Python Source: https://github.com/synthesys-lab/assassyn/blob/master/python/assassyn/utils/README.md Returns the absolute path to the Python package directory (`/python/assassyn`) by appending it to the repository root. This function is used by the builder system to determine package-specific paths for stack inspection and module loading. ```python def package_path() -> str: # ... implementation details ... pass ``` -------------------------------- ### DRAM Memory Request Pattern Example Source: https://github.com/synthesys-lab/assassyn/blob/master/python/assassyn/ir/expr/intrinsic.md Illustrates the pattern for issuing DRAM memory write requests within a condition block. It highlights the scope limitation where the request object is not directly accessible after the block and introduces helper intrinsics to check for and retrieve memory responses. ```python with Condition(we): x = send_write_request(self) # We cannot get x here, as x is outside the scope. # Intrinsics to check for and get memory responses: # has_mem_resp(mem) # get_mem_resp(mem) ``` -------------------------------- ### Global Naming Manager Functions Source: https://github.com/synthesys-lab/assassyn/blob/master/python/assassyn/builder/naming_manager.md Functions to get and set the process-global naming manager instance. ```APIDOC ## Global Naming Manager Functions ### `get_naming_manager() -> Optional[NamingManager]` #### Description Returns the process-global naming manager instance if one has been registered. #### Method `get_naming_manager` #### Returns * Optional[NamingManager] - The global NamingManager instance, or None if not set. ### `set_naming_manager(manager: Optional[NamingManager])` #### Description Registers or clears the global naming manager reference used by decorators and assignment hooks. #### Method `set_naming_manager` #### Parameters * **manager** (Optional[NamingManager]) - Required - The NamingManager instance to register, or None to clear the global reference. ``` -------------------------------- ### Makefile Build Dependency Chain Source: https://github.com/synthesys-lab/assassyn/blob/master/docs/design/internal/build-system.md Illustrates the dependency chain for building a component, ensuring that patches are applied before the build process begins. This guarantees idempotency of build targets and proper reversal of changes during clean operations. ```makefile build- → patch- → .patch-applied marker ``` -------------------------------- ### Type Checking for Array Assignment in Python Source: https://github.com/synthesys-lab/assassyn/blob/master/python/assassyn/ir/array.md Demonstrates type checking for assigning values to elements in a RegArray. It shows successful assignments with matching types and errors with mismatched types. The example also illustrates how RecordValue is automatically unwrapped. ```python # Correct: matching types array = RegArray(UInt(8), 4) value = Const(UInt(8), 42) array[0] = value # ✓ Succeeds # Error: type mismatch wrong_value = Const(UInt(16), 42) array[0] = wrong_value # ✗ Raises TypeError # RecordValue: automatically unwrapped rec_type = Record(a=UInt(8), b=UInt(16)) rec_array = RegArray(rec_type, 4) rec_value = RecordValue(rec_type, a=Const(UInt(8), 1), b=Const(UInt(16), 2)) rec_array[0] = rec_value # ✓ Succeeds, unwraps to Bits ``` -------------------------------- ### Configure and Elaborate Assassyn Backend Source: https://context7.com/synthesys-lab/assassyn/llms.txt Configures simulation parameters, resource paths, and output generation for the Assassyn backend, then elaborates the system design into simulator and Verilog formats. It requires the 'assassyn' library and handles settings like output directory, Verilog generation, simulator generation, simulation thresholds, and resource paths. ```python from assassyn.frontend import * from assassyn.backend import elaborate, config from assassyn import utils # Build the system sys = SysBuilder('my_design') with sys: driver = Driver() driver.build() # Create configuration cfg = config( path='./workspace', # Output directory verilog=True, # Generate SystemVerilog simulator=True, # Generate Rust simulator sim_threshold=1000, # Max simulation cycles idle_threshold=100, # Cycles of inactivity before halt fifo_depth=4, # Default FIFO depth random=False, # Deterministic simulation pretty_printer=True, # Format generated code verbose=True, # Print IR during elaboration resource_base='./resources', # Path to initialization files enable_cache=True # Enable build caching ) # Elaborate the design simulator_path, verilog_path = elaborate(sys, **cfg) # Build and run simulator binary = utils.build_simulator(simulator_path) output = utils.run_simulator(binary_path=binary) # Run Verilator simulation (if available) if verilog_path and utils.has_verilator(): verilog_output = utils.run_verilator(verilog_path) # Check for Verilator availability if utils.has_verilator(): print("Verilator available for RTL simulation") ``` -------------------------------- ### Python: Implement Slice Operator Overloading for Bit Slicing Source: https://github.com/synthesys-lab/assassyn/blob/master/python/assassyn/ir/value.md This method implements the slice operator '[]' for the Value class, enabling bit extraction using slice notation like 'value[start:stop]'. It generates a Slice node for bit extraction. Only slice objects with explicit start and stop values are supported; integer indexing is not allowed. It takes a slice object as input and returns the Slice node. ```python def __getitem__(self, x): ''' Creates a bit slice operation. @param x A slice object with start and stop values @return Slice node for bit extraction ''' # Implementation would typically involve checking if x is a slice # and then calling an IR builder function. # For example: # if isinstance(x, slice) and x.start is not None and x.stop is not None: # return ir_builder.slice_op(self, x.start, x.stop) # else: # raise TypeError("Only slice objects with start and stop are supported") pass ``` -------------------------------- ### Get Memory Clock Period Source: https://github.com/synthesys-lab/assassyn/blob/master/python/assassyn/ramulator2/ramulator2.md Retrieves the memory clock period (tCK) in nanoseconds from an initialized PyRamulator instance. ```APIDOC ## GET /synthesys-lab/assassyn/ramulator2/{instance_id}/memory_tck ### Description Returns the memory clock period (tCK) in nanoseconds for a given PyRamulator instance. ### Method GET ### Endpoint /synthesys-lab/assassyn/ramulator2/{instance_id}/memory_tck ### Parameters #### Path Parameters - **instance_id** (str) - Required - The unique identifier of the PyRamulator instance. ### Response #### Success Response (200) - **tck** (float) - Memory clock period in nanoseconds. #### Response Example ```json { "tck": 1.0 } ``` ``` -------------------------------- ### Initialize Git Submodules Source: https://github.com/synthesys-lab/assassyn/blob/master/README.md This command initializes and updates all Git submodules for the project, ensuring all external dependencies are properly cloned. ```sh git submodule update --init --recursive ``` -------------------------------- ### Get Global Naming Manager Source: https://github.com/synthesys-lab/assassyn/blob/master/python/assassyn/builder/naming_manager.md Returns the process-global naming manager instance if one has been registered. This function allows access to the singleton NamingManager instance. ```python def get_naming_manager() -> Optional[NamingManager]: # Returns the process-global naming manager instance if one has been registered. ``` -------------------------------- ### Build Assassyn Apptainer Container with Makefile Source: https://github.com/synthesys-lab/assassyn/blob/master/vm/apptainer/apptainer.md Instructions for building the Apptainer container for Assassyn using the provided Makefile. Supports default and custom repository URLs and tags. Ensures a reproducible environment by cloning the specified repository. ```makefile make build-apptainer # Build container with custom repository and tag make build-apptainer REPO_URL=https://github.com/your-fork/assassyn REPO_TAG=your-branch # Clean all containers make clean-apptainer ``` -------------------------------- ### Integrate External SystemVerilog Modules in Python Source: https://context7.com/synthesys-lab/assassyn/llms.txt Shows how to use the `ExternalSV` class to wrap SystemVerilog modules. It defines input/output ports using type annotations and specifies SystemVerilog source files, module names, and clock/reset behavior. Parameters can also be overridden. ```python from assassyn.frontend import * @external class ExternalAdder(ExternalSV): # Input ports a: WireIn[UInt(32)] b: WireIn[UInt(32)] # Output ports c: WireOut[UInt(32)] # Metadata __source__ = "path/to/adder.sv" # SystemVerilog source file __module_name__ = "adder" # Module name in Verilog __has_clock__ = False # Combinational module __has_reset__ = False @external class ExternalCounter(ExternalSV): # Inputs enable: WireIn[Bits(1)] reset_val: WireIn[UInt(8)] # Registered output (array access) count: RegOut[UInt(8)] __source__ = "counter.sv" __module_name__ = "counter" __has_clock__ = True __has_reset__ = True # Parameter overrides __parameters__ = { 'WIDTH': 8, 'INIT_FILE': '/path/to/init.hex' } class UseExternal(Module): def __init__(self): super().__init__(ports={ 'x': Port(UInt(32)), 'y': Port(UInt(32)) }) @module.combinational def build(self): x, y = self.pop_all_ports(True) # Instantiate external module (creates ExternalIntrinsic) adder_inst = ExternalAdder(a=x, b=y) # Access output port result = adder_inst.c log("External adder: {} + {} = {}", x, y, result) # For RegOut, use array indexing counter_inst = ExternalCounter( enable=Bits(1)(1), reset_val=UInt(8)(0) ) count_value = counter_inst.count[0] # Index into RegOut ``` -------------------------------- ### Get ArrayRead Index (Python) Source: https://github.com/synthesys-lab/assassyn/blob/master/python/assassyn/ir/expr/array.md Returns the index to read from within the array. This property accesses the second operand stored during initialization. ```python @property def idx(self) -> Value: '''Get the index to read at''' return self._operands[1] ``` -------------------------------- ### Create Directory if Not Exists (Python) Source: https://github.com/synthesys-lab/assassyn/blob/master/python/assassyn/utils/README.md Safely creates a directory, including any necessary parent directories. If the directory already exists, the function does nothing. It uses `os.makedirs` with `exist_ok=True` for robust directory creation. Raises OSError on failure. ```python import os def create_dir(dir_path: str) -> None: # Creates a directory and its parents if they do not exist. # Uses os.makedirs with exist_ok=True. try: os.makedirs(dir_path, exist_ok=True) except OSError as e: # Handle or re-raise the exception raise e ``` -------------------------------- ### Get Array Write Target (Python) Source: https://github.com/synthesys-lab/assassyn/blob/master/python/assassyn/ir/expr/array.md Provides a property to retrieve the target array for an `ArrayWrite` operation. This is the array to which a value will be written. ```python @property def array(self) -> Array: '''Get the array to write to''' return self._operands[0] ``` -------------------------------- ### Get FIFOPush Value (Python) Source: https://github.com/synthesys-lab/assassyn/blob/master/python/assassyn/ir/expr/call.md Retrieves the value that is intended to be pushed through a FIFOPush operation. This is accessed as a property of the FIFOPush IR node. ```python @property def val(self): '''Get the value to push''' return self._operands[1] ``` -------------------------------- ### Python: Instantiate External Module with external_instantiate() Source: https://github.com/synthesys-lab/assassyn/blob/master/python/assassyn/ir/expr/intrinsic.md Instantiates an external SystemVerilog module. This helper function, invoked by the ExternalSV metaclass, takes the external class and input connections. It returns an 'ExternalIntrinsic' object. ```python def external_instantiate(external_class, **inputs) -> ExternalIntrinsic: # Implementation details omitted for brevity pass ``` -------------------------------- ### Get ArrayRead Data Type (Python) Source: https://github.com/synthesys-lab/assassyn/blob/master/python/assassyn/ir/expr/array.md Returns the data type of the value to be read from the array. This is determined by the scalar type of the source array. ```python @property def dtype(self) -> DType: '''Get the data type of the read value''' return self.array.scalar_ty ``` -------------------------------- ### Apply and Reverse Single-Line Patch Source: https://github.com/synthesys-lab/assassyn/blob/master/scripts/patch-apply.md Demonstrates the basic usage of the `patch-apply.sh` script for applying and reversing a simple single-line patch. The patch file `example.patch` modifies a configuration header file. ```bash bash scripts/patch-apply.sh apply example.patch ``` ```bash bash scripts/patch-apply.sh reverse example.patch ``` -------------------------------- ### Visit System Entry Point - Python Source: https://github.com/synthesys-lab/assassyn/blob/master/python/assassyn/ir/visitor.md Serves as the entry point for visiting an entire system. It defines a specific traversal order: first arrays, then modules (setting `current_module`), and finally downstreams (clearing `current_module`). This ensures correct context management during traversal. ```python def visit_system(self, node: SysBuilder): '''Enter a system''' for elem in node.arrays: self.visit_array(elem) for elem in node.modules: self.current_module = elem self.visit_module(elem) self.current_module = None for elem in node.downstreams: self.visit_module(elem) ``` -------------------------------- ### Get Array Users Source: https://github.com/synthesys-lab/assassyn/blob/master/python/assassyn/ir/array.md Returns a list of expressions that reference the array. This property is useful for understanding array dependencies and usage within the Abstract Syntax Tree (AST). ```python @property def users(self) -> typing.List[Expr]: ''' Get the users of the array. @return List of expressions that reference the array. ''' ``` -------------------------------- ### Run Verilator Simulation Workflow Source: https://github.com/synthesys-lab/assassyn/blob/master/python/assassyn/utils/README.md Executes the Verilator simulation workflow within a specified directory. This includes generating Verilog code, patching a specific file, running the testbench, and ensuring the original working directory is restored. ```python def run_verilator(path: str) -> str: """ The helper function to run the verilator. **Parameters:** - `path`: Directory path where the Verilator workflow should be executed **Returns:** - The testbench output as a string """ # Implementation details omitted for brevity pass ``` -------------------------------- ### Get ArrayRead Source Array (Python) Source: https://github.com/synthesys-lab/assassyn/blob/master/python/assassyn/ir/expr/array.md Returns the source array for the array read operation. This property accesses the first operand stored during initialization. ```python @property def array(self) -> Array: '''Get the array to read from''' return self._operands[0] ``` -------------------------------- ### Get Array as Operand String Source: https://github.com/synthesys-lab/assassyn/blob/master/python/assassyn/ir/array.md Converts the array into a string representation suitable for use as an operand in Intermediate Representation (IR) expressions. This method is essential for code generation and analysis. ```python def as_operand(self) -> str: ''' Dump the array as an operand. @return String representing the array's name for use in IR expressions. ''' ``` -------------------------------- ### Run All Project Tests Source: https://github.com/synthesys-lab/assassyn/blob/master/README.md Executes all the tests defined within the project using the 'make test-all' command. This is an optional step to ensure the integrity of the build and functionality. ```sh make test-all # Optional, runs all the tests. ``` -------------------------------- ### Get Array Write Value (Python) Source: https://github.com/synthesys-lab/assassyn/blob/master/python/assassyn/ir/expr/array.md Provides a property to retrieve the value intended to be written to an array during an `ArrayWrite` operation. This is the data being stored at the specified index. ```python @property def val(self) -> Value: '''Get the value to write''' return self._operands[2] ``` -------------------------------- ### Get Global Port Manager Instance (Python) Source: https://github.com/synthesys-lab/assassyn/blob/master/python/assassyn/codegen/simulator/port_mapper.md Retrieves the singleton instance of the PortIndexManager. This ensures a single, consistent manager is used throughout the compilation process for port assignments. ```python def get_port_manager(): """Get the global port manager instance. Returns: The global PortIndexManager instance """ # Implementation details not shown, but it returns the singleton instance ``` -------------------------------- ### Initialize Finite State Machine - Python Source: https://github.com/synthesys-lab/assassyn/blob/master/python/assassyn/ir/module/fsm.md Initializes a finite state machine with a state register and transition table. It validates the state register, stores the transition table, calculates the minimum bits needed for state encoding, and creates a mapping from state names to bit values. ```python class FSM: def __init__(self, state_reg: Array, transition_table: dict): # State Register Validation if not isinstance(state_reg, Array): raise TypeError("state_reg must be an Array object") # Transition Table Storage self.transition_table = transition_table # State Bit Calculation num_states = len(transition_table) self.state_bits = math.floor(math.log2(num_states)) if num_states > 0 else 0 # State Mapping Creation self.state_map = {state: i for i, state in enumerate(transition_table.keys())} # Store state_reg for later use self.state_reg = state_reg print(f"FSM initialized with {num_states} states, requiring {self.state_bits} bits.") print(f"State map: {self.state_map}") ``` -------------------------------- ### Get Read Port Indices - Python Source: https://github.com/synthesys-lab/assassyn/blob/master/python/assassyn/codegen/verilog/array.md Returns a list of read-port indices used by a specific module for a given array. The list is empty if the module does not read the array. ```python def read_port_indices(self, array, module) -> List[int]: """ Returns the list of read-port indices used by module. The list is empty when the module does not read the array. """ pass ``` -------------------------------- ### Get Write Port Index - Python Source: https://github.com/synthesys-lab/assassyn/blob/master/python/assassyn/codegen/verilog/array.md Retrieves the write port index assigned to a specific module for a given array. Returns None if the module does not write to the array. ```python def write_port_index(self, array, module) -> Optional[int]: """ Retrieves the writer port index assigned to module for array. Returns None when the module does not write the array. """ pass ``` -------------------------------- ### Run Rust Simulator Source: https://github.com/synthesys-lab/assassyn/blob/master/python/assassyn/utils/README.md Executes a Rust-based simulator. It can either run a pre-compiled binary directly (faster for multiple runs) or use 'cargo run' if no binary path is provided. Supports offline mode and retries failed builds. ```python def run_simulator(manifest_path: str = None, offline: bool = False, release: bool = True, binary_path: str = None) -> str: """ The helper function to run the simulator. **Parameters:** - `manifest_path`: Path to the Cargo.toml manifest file (optional, used if `binary_path` is None) - `offline`: Whether to run cargo in offline mode (default: False) - `release`: Whether to build in release mode (default: True) - `binary_path`: Path to a pre-compiled simulator binary (optional, for direct execution) **Returns:** - The simulator output as a string """ # Implementation details omitted for brevity pass ``` -------------------------------- ### Format Rust Code with cargo fmt Source: https://github.com/synthesys-lab/assassyn/blob/master/docs/developer/format.md Formats Rust code according to the project's `rustfmt.toml` configuration. This command automatically modifies the code to adhere to the specified style guidelines. ```rust cargo fmt ``` -------------------------------- ### Initialize Simulator and Memory Interface Source: https://github.com/synthesys-lab/assassyn/blob/master/docs/design/internal/simulator.md This snippet shows the initialization of the `Simulator` instance and its memory interface using a provided configuration file path. It requires the `Simulator` struct and its associated `mem_interface` to be defined. The `unsafe` block indicates potential memory safety concerns that need careful handling. ```rust pub fn simulate() { let mut sim = Simulator::new(); unsafe { sim .mem_interface .init("/path/to/example_config.yaml"); } ``` -------------------------------- ### Get FIFOPush FIFO Port (Python) Source: https://github.com/synthesys-lab/assassyn/blob/master/python/assassyn/ir/expr/call.md Retrieves the specific FIFO port to which data will be pushed by a FIFOPush operation. This is accessed as a property of the FIFOPush IR node. ```python @property def fifo(self): '''Get the FIFO port''' return self._operands[0] ``` -------------------------------- ### Makefile Patch-All Target Source: https://github.com/synthesys-lab/assassyn/blob/master/docs/design/internal/build-system.md The `patch-all` target in the Makefile applies all necessary patches on the physical machine before VM initialization. It serves as a unified interface for managing all component patches, ensuring correct path application and consistent patch management. ```makefile patch-all: patch-ramulator2 patch-circt patch-verilator ``` -------------------------------- ### Get Array Write Index (Python) Source: https://github.com/synthesys-lab/assassyn/blob/master/python/assassyn/ir/expr/array.md Provides a property to retrieve the index at which a value will be written in an `ArrayWrite` operation. This operand specifies the position within the target array. ```python @property def idx(self) -> Value: '''Get the index to write at''' return self._operands[1] ``` -------------------------------- ### Get Users for Array - Python Source: https://github.com/synthesys-lab/assassyn/blob/master/python/assassyn/codegen/verilog/array.md Returns a deterministic list of modules that either read or write a given array. This list drives module port generation and top-level wiring. ```python def users_for(self, array) -> List[Module]: """ Returns the deterministic list of modules that either read or write the array. This drives module port generation and top-level wiring. """ pass ``` -------------------------------- ### Implement Conditional Logic with Condition Source: https://context7.com/synthesys-lab/assassyn/llms.txt Shows how to use the `Condition` context manager for hardware-level conditional execution, generating multiplexers and runtime logic. It covers basic conditions, nested conditions, select operations (ternary), and case statements. ```python from assassyn.frontend import * class ConditionalExample(Module): def __init__(self): super().__init__(ports={'enable': Port(Bits(1))}) @module.combinational def build(self): enable = self.pop_all_ports(True) counter = RegArray(UInt(32), 1) result = RegArray(UInt(32), 1) # Hardware conditional - generates mux in RTL # All branches are traced; hardware selects at runtime with Condition(enable[0:0]): (counter & self)[0] <= counter[0] + UInt(32)(1) log("Counter incremented to {}", counter[0]) # Nested conditions high_count = counter[0] > UInt(32)(50) with Condition(high_count): with Condition(enable[0:0]): (result & self)[0] <= counter[0] * UInt(32)(2) # Alternative: select operation (ternary) # cond.select(true_value, false_value) final = enable[0:0].select( counter[0] + UInt(32)(10), # if enable counter[0] # else ) # Case statement state = counter[0][0:1] # 2-bit state output = state.case({ UInt(2)(0): UInt(32)(100), UInt(2)(1): UInt(32)(200), UInt(2)(2): UInt(32)(300), None: UInt(32)(0) # Default case (required) }) ``` -------------------------------- ### Use-Def Graph Construction for Array/Port Operands (Python) Source: https://github.com/synthesys-lab/assassyn/blob/master/python/assassyn/ir/expr/expr.md This snippet illustrates the handling of array and port operands when building the use-def graph. It shows how backward edges are directly registered without requiring a wrapper. ```python if isinstance(operand, (Array, Port)): operand.users.append(self) # Direct backward edge return operand # No wrapper needed ``` -------------------------------- ### Initialize Unique Name Cache Source: https://github.com/synthesys-lab/assassyn/blob/master/python/assassyn/builder/unique_name.md Initializes an empty UniqueNameCache. It sets up an internal dictionary to map prefixes to their last assigned number, starting empty and growing as prefixes are requested. ```python def __init__(self) -> None: pass ``` -------------------------------- ### Get Array Write Data Type (Python) Source: https://github.com/synthesys-lab/assassyn/blob/master/python/assassyn/ir/expr/array.md Returns the data type of the `ArrayWrite` operation. As write operations are side-effecting and do not produce a return value, this property returns `Void()`. ```python @property def dtype(self): '''Get the data type of this operation (Void for side-effect operations)''' from ..dtype import void return void() ``` -------------------------------- ### Get Right-Hand Side Operand - Python Source: https://github.com/synthesys-lab/assassyn/blob/master/python/assassyn/ir/expr/arith.md Retrieves the right-hand side operand from a binary operation node. This property accesses the second element of the internal operands list, which is assumed to be the RHS. ```python @property def rhs(self): '''Get the right-hand side operand''' return self._operands[1] ``` -------------------------------- ### Write Cargo Manifest for Simulator (Python) Source: https://github.com/synthesys-lab/assassyn/blob/master/python/assassyn/codegen/simulator/elaborate.md Writes the Cargo.toml file for a generated simulator crate. It includes a fixed dependency on 'sim-runtime' and dynamically adds dependencies for generated external SystemVerilog bridge crates based on provided FFI specifications. Returns the path to the generated manifest. ```python def _write_manifest(simulator_path: Path, sys_name: str, ffi_specs) -> Path: """Write the Cargo manifest for the generated simulator crate.""" # Implementation details omitted for brevity ``` -------------------------------- ### Visit Module and Generate Rust Implementation (Python) Source: https://github.com/synthesys-lab/assassyn/blob/master/python/assassyn/codegen/simulator/modules.md Visits a module node and generates its corresponding Rust implementation. It handles both internal and external SystemVerilog modules. For external modules, it creates a stub that returns true. For internal modules, it traverses the body and mirrors the simulator's execution model. ```python def visit_module(self, node: Module) -> str: """Visit a module and generate its Rust implementation.""" # Generates a Rust function with signature `pub fn (sim: &mut Simulator) -> bool`. # External SystemVerilog modules that do not have a Python body are short-circuited to `visit_external_module`, # producing a stub that simply returns `true` (the FFI handle drives the real behaviour). # For internal modules the visitor traverses the body and returns `true` on success, mirroring the simulator execution model # where `false` indicates the module was blocked by `wait_until`. pass ``` -------------------------------- ### Get Left-Hand Side Operand - Python Source: https://github.com/synthesys-lab/assassyn/blob/master/python/assassyn/ir/expr/arith.md Retrieves the left-hand side operand from a binary operation node. This property accesses the first element of the internal operands list, which is assumed to be the LHS. ```python @property def lhs(self): '''Get the left-hand side operand''' return self._operands[0] ``` -------------------------------- ### Creating Record Values (Python) Source: https://github.com/synthesys-lab/assassyn/blob/master/docs/design/lang/type.md Demonstrates two methods for creating record values: bundling field values directly or creating a view of an existing raw value. ```python from assassyn.types import Record, UInt Packet = Record(header=UInt(8), payload=UInt(16)) # Create record value from field values packet_from_fields = Packet.bundle(header=0x01, payload=0x1234) # Create record value from existing raw value raw_value = UInt(32)(0x01001234) packet_from_raw = Packet.view(raw_value) ``` -------------------------------- ### Get String Representation of Const Node in Python Source: https://github.com/synthesys-lab/assassyn/blob/master/python/assassyn/ir/const.md Returns a string representation of the Const node, formatted as "(value:dtype)". This method is used for debugging and IR visualization. ```python def __repr__(self) -> str: ''' Return a string representation of the constant. @return String in format "(value:dtype)" ''' ``` -------------------------------- ### Check Build Cache (Python) Source: https://github.com/synthesys-lab/assassyn/blob/master/python/assassyn/utils/README.md Checks if a valid build cache exists for the given source directory and cache key. It verifies the presence and integrity of the `.build_cache.json` file and the existence of cached build artifacts. Returns paths to cached binary and Verilog if valid, otherwise None. ```python import json import os def check_build_cache(src_dir: str, cache_key: str) -> tuple[str, str] | None: # Checks for a valid build cache based on source directory and cache key. # Reads .build_cache.json and verifies artifact existence. cache_file = os.path.join(src_dir, '.build_cache.json') if not os.path.exists(cache_file): return None # ... (rest of the implementation to read and validate cache) return ('path/to/binary', 'path/to/verilog') ``` -------------------------------- ### Get Port Count for Array Initialization (Python) Source: https://github.com/synthesys-lab/assassyn/blob/master/python/assassyn/codegen/simulator/port_mapper.md Shows how to retrieve the number of ports assigned to a specific array. This information is used to initialize the array with the correct number of ports in the generated code. ```python num_ports = port_manager.get_port_count(name) fd.write(f"{name}: Array::new_with_ports({array.size}, {num_ports}),") ``` -------------------------------- ### Get Read Port Index for Expression - Python Source: https://github.com/synthesys-lab/assassyn/blob/master/python/assassyn/codegen/verilog/array.md Looks up the global read-port index allocated to a specific ArrayRead expression. Used by expression lowering and cleanup for referencing generated wires. ```python def read_port_index_for_expr(self, expr) -> Optional[int]: """ Looks up the global read-port index allocated to a specific ArrayRead expression. This is used by expression lowering and cleanup when referencing the generated wires. """ pass ``` -------------------------------- ### Create Default Configuration for System Elaboration (Python) Source: https://github.com/synthesys-lab/assassyn/blob/master/python/assassyn/backend.md The `config` function generates a default configuration dictionary for system elaboration. It accepts various parameters to customize aspects like output paths, verbosity, code generation options (simulator, Verilog), simulation thresholds, FIFO depth, randomization, and caching. It returns a dictionary representing the configuration. ```python def config(path='./workspace', resource_base=None, pretty_printer=True, verbose=True, simulator=True, verilog=False, sim_threshold=100, idle_threshold=100, fifo_depth=4, random=False, enable_cache=True) -> dict: # Function implementation details here ``` -------------------------------- ### Get Current Predicate with get_pred() (Python) Source: https://github.com/synthesys-lab/assassyn/blob/master/docs/design/lang/intrinsics.md Retrieves the current predicate, which is the logical AND of all active conditions on the predicate stack. If the stack is empty, it returns a constant true value. This is useful for guarding operations or assertions. ```python from Tiểu.dsl import get_pred, assume @module.combinational def build(self): # Guard some enable with current predicate enable = get_pred() assume(enable) # example usage ``` -------------------------------- ### Get Owning Module of an Operand Source: https://github.com/synthesys-lab/assassyn/blob/master/python/assassyn/analysis/external_usage.md A helper function to retrieve the module that owns a given operand. It inspects the operand's users and its parent attribute, serving as a foundation for both the index and legacy usage checks. ```python owning_module = get_module(operand) ``` -------------------------------- ### Directory Creation API Source: https://github.com/synthesys-lab/assassyn/blob/master/python/assassyn/backend.md Helper function to create a directory if it does not exist. If the directory already exists, it prints a warning message but continues execution. ```APIDOC ## POST /make_existing_dir ### Description Safely creates directories for output files during elaboration. Handles cases where directories already exist. ### Method POST ### Endpoint /make_existing_dir ### Parameters #### Request Body - **path** (str) - Required - Directory path to create ### Response #### Success Response (200) - **message** (str) - Indicates success or a warning if the directory already existed. #### Response Example ```json { "message": "Directory './workspace' created successfully." } ``` ```json { "message": "Warning: Directory './workspace' already exists." } ``` ```