From eef9168eb55a84735eded6ed999b7d8fea8b2da3 Mon Sep 17 00:00:00 2001 From: ivan Date: Thu, 3 Dec 2026 19:27:02 +0300 Subject: [PATCH 1/4] bugfix (assembler): raise ArgumentOutOfRangeError with the exact error string for out-of-range operands --- assembler.py | 9 ++++++--- src/exception.py | 16 ++++++++++++++++ 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/assembler.py b/assembler.py index 87e0177..7447f9a 100644 --- a/assembler.py +++ b/assembler.py @@ -3,7 +3,7 @@ from io import TextIOWrapper from typing import Generator -from src.exception import (DuplicateLabelError, InvalidArgumentError, +from src.exception import (ArgumentOutOfRangeError, DuplicateLabelError, InvalidArgumentError, MissingArgumentError, UnexpectedArgumentError, UnknownInstructionError) from src.opcodes import ArgOpcode, BasicOpcode @@ -71,11 +71,14 @@ def _translate_file(self, data: list[list]) -> Generator[bytes, None, None]: if argument.upper() in self._label_table: argument = self._label_table[argument.upper()] try: - int(argument) + operand = int(argument) except ValueError: raise InvalidArgumentError(argument, raw_line_num) from None - raw_bytes = struct.pack(">Bi", ArgOpcode[mnemonic], int(argument)) + if mnemonic == "PUSH" and not (-2147483648 <= operand <= 2147483647): + raise ArgumentOutOfRangeError(operand, raw_line_num) + + raw_bytes = struct.pack(">Bi", ArgOpcode[mnemonic], operand) yield raw_bytes else: raise UnknownInstructionError(mnemonic, raw_line_num) diff --git a/src/exception.py b/src/exception.py index d4e8a95..4c36f27 100644 --- a/src/exception.py +++ b/src/exception.py @@ -115,6 +115,22 @@ def __init__( super().__init__("invalid argument", argument, line, *args) +class ArgumentOutOfRangeError(AssemblerError): + """ + Argument is outside the signed 32-bit integer range + """ + + def __init__( + self, argument: int, line: Optional[int] = None, *args: object + ) -> None: + super().__init__( + "argument must be between -2147483648 and 2147483647", + str(argument), + line, + *args, + ) + + class MissingArgumentError(AssemblerError): """ The mnemonic requires an argument, but none has been provided From cbb1a3ad7ba3ffc24dbc6ec43f994fddeddebd5e Mon Sep 17 00:00:00 2001 From: ivan Date: Thu, 3 Dec 2026 20:19:12 +0300 Subject: [PATCH 2/4] feat: add MOD, NEG and comparison mnemonics with documentation --- ISA.md | 18 ++++++++++++++++-- README.md | 6 ++++-- src/opcodes.py | 6 ++++++ vm.py | 20 ++++++++++++++++++++ 4 files changed, 46 insertions(+), 4 deletions(-) diff --git a/ISA.md b/ISA.md index 998d6bb..5bf8655 100644 --- a/ISA.md +++ b/ISA.md @@ -34,6 +34,8 @@ All bytecode instructions and operands are serialized in **Big-Endian (`>`)** by | **DIV** | `0x13` | — | 1 B | `( a, b -- a//b )` | Pops `b`, pops `a`, pushes `a // b` (floor division). | | **INC** | `0x14` | — | 1 B | `( value -- value + 1 )` | Pops `value`, pushes `value += 1` | | **DEC** | `0x15` | — | 1 B | `( value -- value - 1 )` | Pops `value`, pushes `value -= 1` | +| **MOD** | `0x16` | — | 1 B | `( a, b -- a%b )` | Pops `b`, pops `a`, pushes `a % b` (Python remainder semantics). | +| **NEG** | `0x17` | — | 1 B | `( value -- -value )` | Pops `value`, pushes its arithmetic negation. | | **EQ** | `0x20` | — | 1 B | `( a, b -- 1/0 )` | Pops `b`, pops `a`. Pushes 1 if `a == b`, else 0. | | **LT** | `0x21` | — | 1 B | `( a, b -- 1/0 )` | Pops `b`, pops `a`. Pushes 1 if `a < b`, else 0. | | **JMP** | `0x30` | `` | 5 B | `( -- )` | Unconditional jump: sets `PC = addr`. | @@ -42,6 +44,10 @@ All bytecode instructions and operands are serialized in **Big-Endian (`>`)** by | **SWAP** | `0x22` | — | 1 B | `( a, b -- b, a )` | Pops `b`, pops `a`. Pushes `b`, then pushes `a`. | | **OVER** | `0x23` | — | 1 B | `( a, b -- a, b, a )` | Pops `b`, pops `a`. Pushes `a`, `b`, `a`. | | **ROT** | `0x24` | — | 1 B | `( a, b, c -- c, a, b )` | Pops `c`, `b`, `a`. Pushes `b`, `c`, `a`. | +| **GT** | `0x25` | — | 1 B | `( a, b -- 1/0 )` | Pops `b`, pops `a`. Pushes 1 if `a > b`, else 0. | +| **LE** | `0x26` | — | 1 B | `( a, b -- 1/0 )` | Pops `b`, pops `a`. Pushes 1 if `a <= b`, else 0. | +| **GE** | `0x27` | — | 1 B | `( a, b -- 1/0 )` | Pops `b`, pops `a`. Pushes 1 if `a >= b`, else 0. | +| **NEQ** | `0x28` | — | 1 B | `( a, b -- 1/0 )` | Pops `b`, pops `a`. Pushes 1 if `a != b`, else 0. | | **PRINT** | `0x40` | — | 1 B | `( value -- )` | Pops the top element and prints it to `stdout`. | | **GF2P8AFFINEINVQB** | `0x51` | — | 1 B | `( -- )` | Emulates AVX-512 GFNI instruction by printing Linus Torvalds' opinion on it. | @@ -49,7 +55,7 @@ All bytecode instructions and operands are serialized in **Big-Endian (`>`)** by ## 3. Operational Semantics & Edge Cases -### 3.1. Operand Evaluation Order (SUB and DIV) +### 3.1. Operand Evaluation Order and Integer Arithmetic For non-commutative binary operations, the top of the stack is the **right-hand operand** (`b`), and the second element is the **left-hand operand** (`a`). @@ -59,6 +65,14 @@ Evaluation: 10 - 3 = 7 Stack after SUB: [ 7 ] ``` +This order also applies to `DIV`, `MOD`, and comparisons (`EQ`, `LT`, `GT`, `LE`, `GE`, `NEQ`). Comparisons consume two operands and push an integer `1` or `0`. + +`MOD` uses Python's remainder semantics: `a == (a // b) * b + (a % b)` for nonzero `b`. A nonzero remainder has the sign of the divisor: `-10 % 3 == 2`, `10 % -3 == -2`, and `-10 % -3 == -1`. A zero divisor raises `DivisionByZeroError`, as with `DIV`. + +`NEG` consumes one value and changes its sign; zero remains zero. Stack arithmetic uses Python integers without int32 wrapping, so negating `-2147483648` produces `2147483648`. Only immediate operands are limited to signed int32 values. + +`MOD`, `NEG`, `GT`, `LE`, `GE`, and `NEQ` accept no immediate arguments. Mnemonics are case-insensitive. Binary instructions need at least two stack values; `NEG` needs one. Insufficient operands raise `StackUnderflowError`. + ### 3.2. Conditional Branches (`JZ` / `JNZ`) - Both `JZ` and `JNZ` **pop** the condition flag from the stack during evaluation. @@ -69,6 +83,6 @@ Stack after SUB: [ 7 ] The VM core raises dedicated, custom exceptions for the following runtime errors: 1. **`StackUnderflowError`:** Raised when an instruction attempts to pop operands from an empty or insufficiently populated stack. -2. **`DivisionByZeroError`:** Raised when executing `DIV` and the divisor (`b`) is `0`. +2. **`DivisionByZeroError`:** Raised when executing `DIV` or `MOD` and the divisor (`b`) is `0`. 3. **`InvalidOpcodeError`:** Raised when the bytecode stream contains an unrecognized instruction. 4. **`SegmentationFaultError`:** Raised when the `PC` attempts to jump to an invalid instruction address. diff --git a/README.md b/README.md index fca6912..db0ce56 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,7 @@ Full binary layout and instruction semantics are documented in [ISA.md](./ISA.md - **Binary Format:** Big-Endian (`>B` opcodes, `>i` 32-bit signed immediate operands). - **Stack Primitives:** Includes Forth-style stack manipulation (`DUP`, `SWAP`, `OVER`, `ROT`) alongside standard arithmetic, comparisons, and conditional jumps. +- **Arithmetic and Comparisons:** `MOD` computes the remainder, `NEG` changes a value's sign, and `GT`, `LE`, `GE`, `NEQ` complement `EQ` and `LT`. Comparisons produce integer flags (`1` or `0`) for conditional jumps. - **Fault Isolation:** Dedicated exception hierarchies (`AssemblerError`, `VMError`) covering compile-time syntax/label errors and runtime faults (stack underflow, division by zero, invalid opcodes, segmentation faults). ## Usage @@ -27,6 +28,7 @@ Full binary layout and instruction semantics are documented in [ISA.md](./ISA.md ### 1. Assemble source to binary ```bash +mkdir -p build python3 assembler.py examples/num_is_even.asm -o build/num_is_even.bin ``` @@ -64,13 +66,13 @@ done: ## Testing -The project includes 32+ unit and end-to-end tests covering instruction semantics, signed integer edge cases, boundary checks, label resolution, and error handling. +The unit and end-to-end tests cover instruction semantics, label resolution, and error handling. Tests for `MOD`, `NEG`, `GT`, `LE`, `GE`, and `NEQ` check byte encoding and decoding, case-insensitive assembly, rejected immediate arguments, signed integer edge cases, stack underflow, modulo by zero, and conditional branching. ```bash python3 -m venv .venv source .venv/bin/activate pip install pytest -pytest -v +python -m pytest -v ``` ## License diff --git a/src/opcodes.py b/src/opcodes.py index 95855cf..36de3b5 100644 --- a/src/opcodes.py +++ b/src/opcodes.py @@ -19,11 +19,17 @@ class BasicOpcode(Opcode): DIV = 0x13 INC = 0x14 DEC = 0x15 + MOD = 0x16 + NEG = 0x17 EQ = 0x20 LT = 0x21 SWAP = 0x22 OVER = 0x23 ROT = 0x24 + GT = 0x25 + LE = 0x26 + GE = 0x27 + NEQ = 0x28 PRINT = 0x40 GF2P8AFFINEINVQB = 0x51 diff --git a/vm.py b/vm.py index c8f9808..7d947f1 100644 --- a/vm.py +++ b/vm.py @@ -96,6 +96,14 @@ def run_bytecode(self, bytecode: Optional[list[tuple]] = None) -> None: case (BasicOpcode.DEC,): a = self.stack.pop() self.stack.push(a - 1) + case (BasicOpcode.MOD,): + a, b = self.stack.pop_two() + if b == 0: + raise DivisionByZeroError("Division by Zero") + self.stack.push(a % b) + case (BasicOpcode.NEG,): + a = self.stack.pop() + self.stack.push(-a) case (BasicOpcode.EQ,): a, b = self.stack.pop_two() if a == b: @@ -133,6 +141,18 @@ def run_bytecode(self, bytecode: Optional[list[tuple]] = None) -> None: self.stack.push(b) self.stack.push(c) self.stack.push(a) + case (BasicOpcode.GT,): + a, b = self.stack.pop_two() + self.stack.push(int(a > b)) + case (BasicOpcode.LE,): + a, b = self.stack.pop_two() + self.stack.push(int(a <= b)) + case (BasicOpcode.GE,): + a, b = self.stack.pop_two() + self.stack.push(int(a >= b)) + case (BasicOpcode.NEQ,): + a, b = self.stack.pop_two() + self.stack.push(int(a != b)) case (BasicOpcode.PRINT,): a = self.stack.pop() print(a) From ff1b3b5e7444f5fb3030339df01a1ad6e6c038d7 Mon Sep 17 00:00:00 2001 From: ivan Date: Thu, 3 Dec 2026 21:36:20 +0300 Subject: [PATCH 3/4] fix(assembler): validate int32 range for all immediate operands --- assembler.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/assembler.py b/assembler.py index 7447f9a..44d085f 100644 --- a/assembler.py +++ b/assembler.py @@ -75,7 +75,7 @@ def _translate_file(self, data: list[list]) -> Generator[bytes, None, None]: except ValueError: raise InvalidArgumentError(argument, raw_line_num) from None - if mnemonic == "PUSH" and not (-2147483648 <= operand <= 2147483647): + if not (-2147483648 <= operand <= 2147483647): raise ArgumentOutOfRangeError(operand, raw_line_num) raw_bytes = struct.pack(">Bi", ArgOpcode[mnemonic], operand) From 5aa9edf886c9d946487743696480e20ee701d60b Mon Sep 17 00:00:00 2001 From: cortex <41265844+by-cortex@users.noreply.github.com> Date: Thu, 3 Dec 2026 19:03:28 +0000 Subject: [PATCH 4/4] feat: clarify testing coverage in README --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index db0ce56..0a85aae 100644 --- a/README.md +++ b/README.md @@ -66,7 +66,7 @@ done: ## Testing -The unit and end-to-end tests cover instruction semantics, label resolution, and error handling. Tests for `MOD`, `NEG`, `GT`, `LE`, `GE`, and `NEQ` check byte encoding and decoding, case-insensitive assembly, rejected immediate arguments, signed integer edge cases, stack underflow, modulo by zero, and conditional branching. +The project includes 32+ unit and end-to-end tests covering instruction semantics, signed integer edge cases, boundary checks, label resolution, and error handling. ```bash python3 -m venv .venv