### Tiny8 Initialization Example Source: https://github.com/sql-hkr/tiny8/blob/main/docs/assembly_language.md Shows how to initialize working registers and memory at the beginning of a Tiny8 program using `ldi` and `sts` instructions. ```asm ; Initialize working registers ldi r16, 0 ; Counter ldi r17, 1 ; Accumulator ldi r18, 10 ; Loop limit ; Initialize memory if needed ldi r19, 0xFF sts 0x0200, r19 ; Store initial value ``` -------------------------------- ### Set Up Development Environment with uv Source: https://github.com/sql-hkr/tiny8/blob/main/CONTRIBUTING.md Instructions for setting up a Python development environment using 'uv' for dependency management. It covers installing uv, creating a virtual environment, and installing project dependencies. ```bash # Install uv if you haven't already # macOS/Linux: curl -LsSf https://astral.sh/uv/install.sh | sh # Windows: powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex" # Create virtual environment and install dependencies uv venv source .venv/bin/activate # On Windows: .venv\Scripts\activate uv sync ``` -------------------------------- ### Verify Development Setup Source: https://github.com/sql-hkr/tiny8/blob/main/CONTRIBUTING.md Commands to verify the development setup by running tests, checking code linting, and trying the command-line interface (CLI) of the Tiny8 simulator. ```bash # Run tests pytest # Check linting ruff check . # Try the CLI tiny8 examples/fibonacci.asm ``` -------------------------------- ### Install Tiny8 with Pip Source: https://github.com/sql-hkr/tiny8/blob/main/docs/index.md Installs the Tiny8 package using pip, a Python package installer. This is the primary method for setting up Tiny8 on your system. ```bash pip install tiny8 ``` -------------------------------- ### Tiny8 Two-Pass Assembly Example Source: https://github.com/sql-hkr/tiny8/blob/main/docs/assembly_language.md Explains and demonstrates the two-pass assembly process in Tiny8, which allows for forward references by first collecting labels and then resolving references. ```asm ; Forward reference (allowed) jmp forward_label nop nop forward_label: ret ``` -------------------------------- ### Set Up Development Environment with pip Source: https://github.com/sql-hkr/tiny8/blob/main/CONTRIBUTING.md Instructions for setting up a Python development environment using the standard 'pip' and 'venv' modules. It covers creating a virtual environment and installing project dependencies. ```bash python -m venv .venv source .venv/bin/activate # On Windows: .venv\Scripts\activate pip install -e ".[dev]" ``` -------------------------------- ### Visualize Bubble Sort Algorithm (Bash) Source: https://github.com/sql-hkr/tiny8/blob/main/docs/visualization.md A command-line example demonstrating the visualization of a bubble sort algorithm. This helps in observing register changes and memory swaps during the sorting process. ```bash # Visualize bubble sort tiny8 examples/bubblesort.asm -m ani -o bubblesort.gif ``` -------------------------------- ### Run Tiny8 Assembly Example with Interactive Debugger Source: https://github.com/sql-hkr/tiny8/blob/main/docs/examples/index.md Demonstrates how to execute a Tiny8 assembly program using the interactive debugger. This is useful for stepping through code and understanding its execution flow. No external dependencies are required beyond the `tiny8` tool. ```bash tiny8 examples/fibonacci.asm ``` -------------------------------- ### Visualize Fibonacci Sequence Generation (Bash) Source: https://github.com/sql-hkr/tiny8/blob/main/docs/visualization.md A command-line example for visualizing the generation of a Fibonacci sequence. This aids in tracking register values, loop counters, and flag changes during the iterative process. ```bash # Track Fibonacci sequence generation tiny8 examples/fibonacci.asm -m ani -o fib.gif ``` -------------------------------- ### Python Type Hinting and Docstring Example Source: https://github.com/sql-hkr/tiny8/blob/main/CONTRIBUTING.md An example demonstrating Python code style guidelines, including type hints for function signatures and Google-style docstrings for documenting functions, arguments, and potential exceptions. ```python def execute_instruction(self, opcode: int, operands: list[int]) -> None: """Execute a single instruction. Args: opcode: The instruction opcode. operands: List of operand values. Raises: InvalidOpcodeError: If opcode is not recognized. """ # Implementation ``` -------------------------------- ### Tiny8 Assembly Example Template Source: https://github.com/sql-hkr/tiny8/blob/main/CONTRIBUTING.md A template for creating example assembly files in the 'examples/' directory. It includes sections for algorithm name, description, explanation, registers used, and expected results, followed by a basic code structure. ```asm ; Algorithm Name ; Brief description of what this program does ; ; Algorithm explanation: ; - Step 1 description ; - Step 2 description ; ; Registers used: ; - R16: Purpose ; - R17: Purpose ; ; Expected result: Description ldi r16, 0 ; Initialize ; ... your code done: jmp done ; Halt ``` -------------------------------- ### Tiny8 Code Organization Best Practice Source: https://github.com/sql-hkr/tiny8/blob/main/docs/assembly_language.md Provides an example of well-organized Tiny8 assembly code, emphasizing meaningful labels, comments, grouping related code, and using blank lines for separation. ```asm ; Good: Clear structure and documentation ; Calculate factorial of N ; Input: R16 = N ; Output: R17 = N! factorial: ldi r17, 1 ; result = 1 fact_loop: mul r17, r16 ; result *= N dec r16 ; N-- brne fact_loop ; Continue if N != 0 ret ``` -------------------------------- ### Tiny8 Assembly: Store 'HELLO' String in Memory Source: https://github.com/sql-hkr/tiny8/blob/main/docs/examples/hello_world.md This Tiny8 assembly program demonstrates how to store the ASCII characters for 'HELLO' into sequential memory locations starting at address 0x60. It utilizes immediate load instructions (ldi) to load values into registers and store instructions (st) to write register contents to memory. The program concludes with an infinite loop to halt execution. ```asm ; Hello World - Store ASCII string "HELLO" in memory ; Demonstrates basic memory store operations ; Output: RAM[0x60..0x64] contains "HELLO" in ASCII start: ldi r16, 0x60 ; Base address ldi r17, 72 ; 'H' st r16, r17 inc r16 ldi r17, 69 ; 'E' st r16, r17 inc r16 ldi r17, 76 ; 'L' st r16, r17 inc r16 st r16, r17 ; 'L' (reuse value) inc r16 ldi r17, 79 ; 'O' st r16, r17 done: jmp done ; infinite loop (halt) ``` -------------------------------- ### Run Bubble Sort Example in CLI and Animation Modes Source: https://github.com/sql-hkr/tiny8/blob/main/README.md Demonstrates how to execute the Bubble Sort assembly program using the Tiny8 CLI. It shows commands for interactive debugging with specified memory ranges and for generating an animated GIF of the sorting process. ```bash tiny8 examples/bubblesort.asm -ms 0x60 -me 0x80 # Watch live tiny8 examples/bubblesort.asm -m ani -o sort.gif -ms 0x60 -me 0x80 # Create GIF ``` -------------------------------- ### Verify Tiny8 Installation Source: https://github.com/sql-hkr/tiny8/blob/main/docs/getting_started.md Checks if the Tiny8 installation was successful by displaying its version number in the terminal. ```bash tiny8 --version ``` -------------------------------- ### Conventional Commit Message Example Source: https://github.com/sql-hkr/tiny8/blob/main/CONTRIBUTING.md An example demonstrating the conventional commit message format, including type, summary, body, and footer for referencing issues. This format helps in automating changelog generation and understanding commit history. ```git feat: add MUL instruction support - Implement 8-bit multiplication - Update instruction decoder - Add comprehensive tests - Update documentation Closes #123 ``` -------------------------------- ### Fibonacci Assembly Program for Tiny8 Source: https://github.com/sql-hkr/tiny8/blob/main/docs/index.md An example assembly program for the Tiny8 simulator that calculates the 10th Fibonacci number. It demonstrates basic instructions like load immediate (ldi), add, move (mov), decrement (dec), and conditional branch (brne). ```asm ; Fibonacci Sequence Calculator ; Calculates the 10th Fibonacci number (F(10) = 55) ldi r16, 0 ; F(0) = 0 ldi r17, 1 ; F(1) = 1 ldi r18, 9 ; Counter: 9 more iterations loop: add r16, r17 ; F(n) = F(n-1) + F(n-2) mov r19, r16 ; Save result temporarily mov r16, r17 ; Shift: previous = current mov r17, r19 ; Shift: current = new result dec r18 ; Decrement counter brne loop ; Continue if counter != 0 done: jmp done ; Infinite loop at end ``` -------------------------------- ### Generate Animation of Tiny8 Assembly Execution Source: https://github.com/sql-hkr/tiny8/blob/main/docs/examples/index.md Shows how to generate an animated GIF from the execution of a Tiny8 assembly program. This feature is helpful for visualizing complex algorithms like bubble sort. Requires the `tiny8` tool and an output file path. ```bash tiny8 examples/bubblesort.asm -m ani -o bubblesort.gif ``` -------------------------------- ### Run Tiny8 Assembly Program from CLI Source: https://github.com/sql-hkr/tiny8/blob/main/docs/index.md Executes an assembly program using the Tiny8 command-line interface. This command starts the interactive debugger for the specified assembly file. ```bash tiny8 fibonacci.asm ``` -------------------------------- ### Run Tiny8 Assembly Program using Python API Source: https://github.com/sql-hkr/tiny8/blob/main/docs/examples/index.md Illustrates how to load and run a Tiny8 assembly program using the Python API. This involves creating a CPU instance, assembling the file, and executing the program with a step limit. Requires the `tiny8` Python library. ```python from tiny8 import CPU, assemble_file cpu = CPU() cpu.load_program(assemble_file("examples/fibonacci.asm")) cpu.run(max_steps=1000) ``` -------------------------------- ### Typical Tiny8 Program Layout Source: https://github.com/sql-hkr/tiny8/blob/main/docs/assembly_language.md Illustrates the standard structure of a Tiny8 program, including header comments, initialization, main loop, subroutines, and program termination with an infinite loop. ```asm ; ============================================ ; Program: Description ; Author: Your Name ; Description: What the program does ; ============================================ ; --- Initialization --- ldi r16, initial_value ldi r17, 0 ; --- Main Loop --- main_loop: ; ... main program logic ... jmp main_loop ; --- Subroutines --- subroutine1: ; ... subroutine code ... ret subroutine2: ; ... subroutine code ... ret ; --- End --- done: jmp done ; Infinite loop ``` -------------------------------- ### Tiny8 Memory Access Examples (Assembly) Source: https://github.com/sql-hkr/tiny8/blob/main/docs/architecture.md Demonstrates how to load data from and store data to memory using register-indirect addressing in Tiny8 assembly. It involves setting up address pointers in specific registers (R26, R27) and then using the 'ld' (load) and 'st' (store) instructions. ```text ldi r26, 0x00 ; Set address low byte ldi r27, 0x02 ; Set address high byte (address = 0x0200) ld r16, r26 ; Load byte from address in R26 into R16 ; Store to memory ldi r26, 0x50 ; Address = 0x50 ldi r16, 42 ; Value to store st r26, r16 ; Store R16 to memory[R26] ``` -------------------------------- ### Tiny8 Assembly: Valid and Invalid Labels Source: https://github.com/sql-hkr/tiny8/blob/main/docs/assembly_language.md Provides examples of valid and invalid label definitions in Tiny8 assembly. Labels must end with a colon, be case-sensitive, and adhere to character restrictions (letters, digits, underscore), not starting with a digit and not being reserved mnemonics. ```asm start: loop_1: CalculateFibonacci: _private: ``` -------------------------------- ### CPU Class Initialization and Program Execution in Python Source: https://context7.com/sql-hkr/tiny8/llms.txt Demonstrates how to initialize the CPU, assemble and load a program, execute it with a step limit, read register and memory values, check status flags, and inspect the execution trace. Requires the 'tiny8' library and 'matplotlib' for visualization. ```python from tiny8 import CPU, assemble_file # Create CPU instance with default memory cpu = CPU() # Assemble and load program asm = assemble_file("examples/fibonacci.asm") cpu.load_program(asm) # Execute program with step limit cpu.run(max_steps=1000, show_progress=True) # Read final register values result = cpu.read_reg(17) # R17 contains 10th Fibonacci number (55) print(f"Fibonacci F(10) = {result}") # Access memory cpu.write_ram(0x100, 42) value = cpu.read_ram(0x100) # Check status register flags zero_flag = cpu.get_flag(1) # SREG bit 1 (Z flag) carry_flag = cpu.get_flag(0) # SREG bit 0 (C flag) # Inspect execution trace for step in cpu.step_trace[:5]: print(f"Step {step['step']}: PC=0x{step['pc']:04X}, {step['instr']}") print(f" Registers: {step['regs'][:8]}") # First 8 registers print(f" SREG: 0x{step['sreg']:02X}") ``` -------------------------------- ### Tiny8 Assembly: Example Program for Summation Source: https://github.com/sql-hkr/tiny8/blob/main/docs/assembly_language.md This example demonstrates a basic Tiny8 assembly program to calculate the sum of numbers from 1 to N. It utilizes instructions for loading immediate values, arithmetic operations, comparisons, and branching. N is expected to be in register R16, and the result is stored in R17. ```asm ; Calculate the sum of 1 to N ; N is stored in R16, result in R17 ldi r16, 10 ; N = 10 ldi r17, 0 ; Sum = 0 ldi r18, 1 ; Counter = 1 loop: add r17, r18 ; Sum += Counter inc r18 ; Counter++ cp r18, r16 ; Compare Counter with N brlo loop ; Loop if Counter < N breq loop ; Loop if Counter == N done: jmp done ; Infinite loop ``` -------------------------------- ### Tiny8 Case Sensitivity Rules Source: https://github.com/sql-hkr/tiny8/blob/main/docs/assembly_language.md Demonstrates the case sensitivity rules for Tiny8 assembly. Instructions and registers are case-insensitive, while labels are case-sensitive. This example shows equivalent instructions and distinct labels. ```asm ; These are all equivalent ADD r16, r17 add r16, r17 Add R16, R17 ; But these labels are different Loop: ; ... jmp loop ; Error! Label "loop" not defined ``` -------------------------------- ### Tiny8 Value Range and Overflow Example Source: https://github.com/sql-hkr/tiny8/blob/main/docs/assembly_language.md Illustrates the 8-bit value ranges (0-255 unsigned, -128 to +127 signed) in Tiny8 and how overflow occurs with wrap-around behavior using `inc` and `dec`. ```asm ldi r16, 255 inc r16 ; R16 = 0 (wraps around) ldi r17, 0 dec r17 ; R17 = 255 (wraps around) ``` -------------------------------- ### Tiny8 Assembly: Single-Line Comments Source: https://github.com/sql-hkr/tiny8/blob/main/docs/assembly_language.md Demonstrates the usage of single-line comments in Tiny8 assembly. Comments start with a semicolon (`;`) and extend to the end of the line, aiding in code documentation. These comments are ignored by the assembler. ```asm ldi r16, 42 ; Load the answer ; This is a full-line comment add r16, r17 ; Add registers ``` -------------------------------- ### Tiny8 Assembly: Instruction Format and Operand Counts Source: https://github.com/sql-hkr/tiny8/blob/main/docs/assembly_language.md Explains the general structure of Tiny8 assembly instructions, which follows the pattern `[label:] mnemonic [operand1[, operand2[, ...]]]`. It also provides examples of instructions with zero, one, or two operands. ```asm ; Zero operands nop ; No operation ret ; Return from subroutine ; One operand inc r16 ; Increment register dec r17 ; Decrement register jmp loop ; Jump to label push r16 ; Push register ; Two operands mov r16, r17 ; Move R17 to R16 add r16, r17 ; Add R17 to R16 ldi r16, 42 ; Load immediate into R16 lds r16, 0x0200 ; Load from memory ``` -------------------------------- ### Tiny8 CLI Command Syntax and General Options Source: https://github.com/sql-hkr/tiny8/blob/main/README.md Illustrates the basic command structure for the Tiny8 CLI tool, specifying the file and optional arguments. It also lists general options available for controlling the execution and displaying information. ```bash tiny8 FILE [OPTIONS] General Options: | Option | Description | |--------|-------------| | -m, --mode {cli,ani} | Visualization mode: `cli` for interactive debugger (default), `ani` for animation | | -v, --version | Show version and exit | | --max-steps N | Maximum execution steps (default: `15000`) ``` -------------------------------- ### Testing with Pytest Source: https://github.com/sql-hkr/tiny8/blob/main/README.md Demonstrates common pytest commands for running tests, including running all tests, running tests with coverage reporting (generating an HTML report), and running tests from a specific file. ```bash pytest pytest --cov=src/tiny8 --cov-report=html pytest tests/test_arithmetic.py ``` -------------------------------- ### Tiny8 Assembly: Loop Structure Example Source: https://github.com/sql-hkr/tiny8/blob/main/docs/examples/fibonacci.md This assembly snippet illustrates a common loop structure used in embedded programming. It initializes a counter register (R18) to a specific value (N) and then enters a loop. Inside the loop, operations are performed, followed by decrementing the counter and branching back to the loop's start if the counter is not zero. This pattern is fundamental for repetitive tasks. ```asm ldi r18, N ; Initialize counter loop: ; ... loop body ... dec r18 ; Decrement counter brne loop ; Branch if not equal to zero ``` -------------------------------- ### CPU Class Initialization and Program Execution Source: https://context7.com/sql-hkr/tiny8/llms.txt This section details how to initialize the CPU, load and execute assembly programs, and read register and memory values. It also covers accessing status register flags and inspecting the execution trace. ```APIDOC ## CPU Class Initialization and Program Execution ### Description Initializes the core 8-bit CPU simulator, loads assembly programs, executes them, and provides methods to inspect the CPU's state, including registers, memory, and status flags. ### Method Python Class Methods ### Parameters N/A (Class methods) ### Request Example ```python from tiny8 import CPU, assemble_file # Create CPU instance with default memory cpu = CPU() # Assemble and load program asm = assemble_file("examples/fibonacci.asm") cpu.load_program(asm) # Execute program with step limit cpu.run(max_steps=1000, show_progress=True) # Read final register values result = cpu.read_reg(17) # R17 contains 10th Fibonacci number (55) print(f"Fibonacci F(10) = {result}") # Access memory cpu.write_ram(0x100, 42) value = cpu.read_ram(0x100) # Check status register flags zero_flag = cpu.get_flag(1) # SREG bit 1 (Z flag) carry_flag = cpu.get_flag(0) # SREG bit 0 (C flag) # Inspect execution trace for step in cpu.step_trace[:5]: print(f"Step {step['step']}: PC=0x{step['pc']:04X}, {step['instr']}") print(f" Registers: {step['regs'][:8]}") # First 8 registers print(f" SREG: 0x{step['sreg']:02X}") ``` ### Response #### Success Response Execution results, register values, memory contents, status flags, and execution trace data. #### Response Example ```json { "result": 55, "memory_value_at_0x100": 42, "zero_flag": 0, "carry_flag": 0, "execution_trace_sample": [ { "step": 1, "pc": "0x0000", "instr": "LDI R16, 0", "regs": [0, 0, ...], "sreg": "0x00" } ] } ``` ``` -------------------------------- ### Pytest Example Test Structure Source: https://github.com/sql-hkr/tiny8/blob/main/CONTRIBUTING.md An example structure for writing a test case using the pytest framework in Python. It demonstrates the Arrange-Act-Assert pattern for testing CPU functionality. ```python def test_feature_name(): """Test description.""" # Arrange cpu = CPU() cpu.load_program(...) # Act cpu.step() # Assert assert cpu.read_reg(16) == expected_value ``` -------------------------------- ### Control tiny8 Execution and Visualization via CLI Source: https://context7.com/sql-hkr/tiny8/llms.txt The command-line interface (CLI) tool allows for assembly, execution, and visualization of programs. It supports basic execution with an interactive debugger, animated visualization generation, custom memory range display, adjustable playback speed, and high-quality video output with configurable settings. ```bash # Basic execution with interactive debugger tiny8 program.asm # Generate animated visualization tiny8 fibonacci.asm -m ani -o fibonacci.gif # Custom memory range display (hex addresses supported) tiny8 bubblesort.asm --mem-start 0x60 --mem-end 0x7F # Slow playback for teaching (0.5 seconds per step) tiny8 program.asm -d 0.5 # High-quality video with custom settings tiny8 bubblesort.asm -m ani -o output.mp4 \ --fps 30 \ --plot-every 50 \ --mem-start 96 \ --mem-end 127 # Long-running program with increased step limit tiny8 complex.asm --max-steps 50000 # Fast animation generation tiny8 program.asm -m ani -o demo.gif -f 60 -i 1 -pe 200 ``` -------------------------------- ### Create Animation using Python API Source: https://github.com/sql-hkr/tiny8/blob/main/docs/visualization.md Demonstrates how to programmatically create an execution animation using the tiny8 Python API. This involves assembling code, running it on a simulated CPU, and then using the Visualizer class to generate the animation file. ```python from tiny8 import CPU, assemble, Visualizer # Create and run program code = """ ldi r16, 0 ldi r17, 10 loop: add r16, r17 dec r17 brne loop """ asm = assemble(code) cpu = CPU() cpu.load_program(asm) cpu.run(max_steps=100) # Create visualization viz = Visualizer(cpu) viz.animate_execution( mem_addr_start=0x0200, mem_addr_end=0x02FF, filename="my_animation.gif", interval=200, # ms between frames fps=30, cmap="viridis" # matplotlib colormap ) ``` -------------------------------- ### Tiny8 Assembly: Loading Immediate Values Source: https://github.com/sql-hkr/tiny8/blob/main/docs/getting_started.md Illustrates how to load immediate values into registers using different number formats: decimal, hexadecimal, and binary. ```asm ldi r16, 42 ; Load decimal lDi r17, 0xFF ; Load hexadecimal lDi r18, 0b1010 ; Load binary ``` -------------------------------- ### Use Tiny8 Python API to Run Program Source: https://github.com/sql-hkr/tiny8/blob/main/docs/index.md Demonstrates how to use the Tiny8 Python API to assemble and run an assembly program. It involves importing the CPU and assemble_file functions, loading the program, running it, and reading the result from a register. ```python from tiny8 import CPU, assemble_file # Assemble and load program asm = assemble_file("fibonacci.asm") cpu = CPU() cpu.load_program(asm) # Run the program cpu.run(max_steps=1000) # Check the result print(f"Result: R17 = {cpu.read_reg(17)}") # Final Fibonacci number ``` -------------------------------- ### Reverse Array in Place using Tiny8 Assembly Source: https://github.com/sql-hkr/tiny8/blob/main/docs/examples/reverse.md This code snippet reverses an array stored in RAM starting at address 0x60. It uses two pointers, one starting at the beginning of the array and the other at the end. The pointers move towards each other, swapping the elements they point to until they meet or cross. The array is modified in place. ```assembly ; Reverse: reverse array [10, 20, 30, 40, 50, 60] ; Output: RAM[0x60..0x65] = [60, 50, 40, 30, 20, 10] start: ; store array at RAM[0x60..0x65] ldi r20, 0x60 ldi r21, 10 st r20, r21 ldi r20, 0x61 ldi r21, 20 st r20, r21 ldi r20, 0x62 ldi r21, 30 st r20, r21 ldi r20, 0x63 ldi r21, 40 st r20, r21 ldi r20, 0x64 ldi r21, 50 st r20, r21 ldi r20, 0x65 ldi r21, 60 st r20, r21 ; reverse: swap from both ends ldi r16, 0x60 ; left = 0x60 ldi r17, 0x65 ; right = 0x65 reverse_loop: ; check if left >= right cp r16, r17 brge done ; swap RAM[left] and RAM[right] ld r18, r16 ; temp = RAM[left] ld r19, r17 ; RAM[left] = RAM[right] st r16, r19 st r17, r18 ; RAM[right] = temp ; move pointers inc r16 ; left++ dec r17 ; right-- jmp reverse_loop done: jmp done ``` -------------------------------- ### Execute Tiny8 Assembly Program using Python Source: https://github.com/sql-hkr/tiny8/blob/main/README.md Shows how to use the Tiny8 Python library to assemble and run an assembly file. It demonstrates loading a program, executing it, and then reading the modified memory contents to verify the sorting result. ```python from tiny8 import CPU, assemble_file cpu = CPU() cpu.load_program(assemble_file("examples/bubblesort.asm")) cpu.run() print("Sorted:", [cpu.read_ram(i) for i in range(0x60, 0x80)]) ``` -------------------------------- ### Assembly Language Programming and Parsing in Python Source: https://context7.com/sql-hkr/tiny8/llms.txt Shows how to assemble inline assembly code using the 'assemble' function, which returns program length, labels, and the instruction list. It then demonstrates loading and executing this assembled program with the CPU class and retrieving results. Requires the 'tiny8' library. ```python from tiny8 import assemble, CPU # Assemble inline assembly code asm_code = """ ; Calculate sum of 1 to N ldi r16, 0 ; sum = 0 ldi r17, 1 ; i = 1 ldi r18, 10 ; N = 10 loop: add r16, r17 ; sum += i inc r17 ; i++ ldi r19, 11 cp r17, r19 ; compare i with N+1 brne loop ; continue if i != N+1 done: jmp done ; halt """ result = assemble(asm_code) print(f"Program length: {len(result.program)} instructions") print(f"Labels: {result.labels}") # {'loop': 3, 'done': 8} print(f"First instruction: {result.program[0]}") # ('LDI', (('reg', 16), 0)) # Execute assembled program cpu = CPU() cpu.load_program(result) cpu.run(max_steps=200) sum_result = cpu.read_reg(16) print(f"Sum of 1 to 10 = {sum_result}") # 55 ``` -------------------------------- ### Tiny8 Number Parsing Formats Source: https://github.com/sql-hkr/tiny8/blob/main/docs/assembly_language.md Shows the different number formats recognized by the Tiny8 assembler, including decimal, negative decimal, hexadecimal (0x and $), and binary. ```asm ; Decimal: 42 ; Negative decimal: -10 (stored as 246 in 8-bit) ; Hexadecimal (0x): 0xFF (255) ; Hexadecimal ($): $FF (255) ; Binary: 0b11111111 (255) ``` -------------------------------- ### Tiny8 Program Termination Source: https://github.com/sql-hkr/tiny8/blob/main/docs/assembly_language.md Illustrates methods for program termination in Tiny8 assembly, typically by creating an infinite loop using `jmp` or a `nop` and `jmp` sequence. ```asm done: jmp done ; Loop forever ; Or explicitly spin end: nop jmp end ``` -------------------------------- ### Interactive CLI Debugger Usage in Python Source: https://context7.com/sql-hkr/tiny8/llms.txt Illustrates launching the terminal-based CLI debugger for a given CPU state. It allows step-through execution, memory inspection, and utilizes various keyboard commands for navigation, searching, and state modification. Requires 'tiny8' library and a pre-assembled program. ```python from tiny8 import CPU, assemble_file, run_cli # Prepare and execute program asm = assemble_file("examples/bubblesort.asm") cpu = CPU() cpu.load_program(asm) cpu.run(max_steps=10000) # Launch interactive debugger # Shows memory range 0x60-0x7F where array is stored # Delay of 0.2s between auto-advance steps run_cli( cpu, mem_addr_start=0x60, mem_addr_end=0x7F, delay=0.2, source_lines=asm.source_lines ) # CLI keyboard commands (used interactively): # l/h or ←/→ : step forward/backward # w/b : jump ±10 steps # 0/$ : first/last step # Space : play/pause # [/] : slower/faster playback # r : toggle all registers / changed only # M : toggle all memory / non-zero only # j/k : scroll memory view # :123 : jump to step 123 # :+50 : jump forward 50 steps # :/ldi : search forward for "ldi" instruction # :?add : search backward for "add" instruction # :@0x100 : jump to PC address 0x100 # :r16 : find next change to register R16 # :r16=42 : find where R16 equals 42 # :m100 : find next change to memory[100] # :m0x60=0xFF : find where memory[0x60] equals 0xFF # :fZ : find next change to Zero flag # :fC=1 : find where Carry flag equals 1 # ma : set mark 'a' # 'a : jump to mark 'a' ```