Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 16 additions & 2 deletions ISA.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` | `<addr>` | 5 B | `( -- )` | Unconditional jump: sets `PC = addr`. |
Expand All @@ -42,14 +44,18 @@ 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. |

---

## 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`).

Expand All @@ -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.
Expand All @@ -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.
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,15 @@ 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

### 1. Assemble source to binary

```bash
mkdir -p build
python3 assembler.py examples/num_is_even.asm -o build/num_is_even.bin
```

Expand Down Expand Up @@ -70,7 +72,7 @@ The project includes 32+ unit and end-to-end tests covering instruction semantic
python3 -m venv .venv
source .venv/bin/activate
pip install pytest
pytest -v
python -m pytest -v
```

## License
Expand Down
9 changes: 6 additions & 3 deletions assembler.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 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)
Expand Down
16 changes: 16 additions & 0 deletions src/exception.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 6 additions & 0 deletions src/opcodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
20 changes: 20 additions & 0 deletions vm.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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)
Expand Down
Loading