Files
slipcompiler/SlipcodeCompilationTest.ipynb
T

6.0 KiB

In [4]:
instruction_opcodes = {
    "IDK": 0x00,
    "LIT": 0x01,
    "SWAP": 0x02,
    "DEL": 0x03,
    "COPY": 0x04,
    "DEF": 0x05,
    "END": 0x06,
    "ADD": 0x10,
    "SUB": 0x11,
    "MUL": 0x12,
    "DIV": 0x13,
    "POW": 0x14,
    "SQRT": 0x15,
    "ONEMIN": 0x16,
    "ROUND": 0x17,
    "CEIL": 0x18,
    "FLOOR": 0x19,
    "MOD": 0x1a,
    "FRACT": 0x1b,
    "COMP": 0x1c,
    "LERP": 0x1d,
    "MIN": 0x1e,
    "MAX": 0x1f
}

type_opcodes = {
    "BOOL": {"code": 0x00, "length": 1},
    "INT": {"code": 0x01, "length": 4},
    "FLT": {"code": 0x02, "length": 4},
    "VEC": {"code": 0x03, "length": 12}
}
In [5]:
source_file = open("Test.slc")
source_code = source_file.read()
source_code = source_code.replace(" ", "\n")
source_code = source_code.split("\n")
In [6]:
import struct

byte_code = bytearray()
code_type = ""
lit_type = ""
for word in source_code:
    print(f"{word}, {code_type}")
    # Handle literal types
    if code_type == "lit_type":
        print("Parsing literal type...")

        # Consume a literal of this word's type next
        code_type = "literal"
        lit_type = word

        # Push the type opcode onto the instruction stack
        byte_code.append(type_opcodes[word]["code"])
        continue
    # Handle literal values
    if code_type == "literal":
        print("Parsing literal value...")

        # Consume a generic command next
        code_type = ""

        # Handle float literals
        if lit_type == "FLT":
            lit_bytes = bytearray(struct.pack(">f", float(word)))
            byte_code.extend(lit_bytes)
        # Handle vector literals
        if lit_type == "VEC":
            # Creates an array of floats from a string like "-1.0,7.3,10.5"
            vector_components = word.split(",")
            for component in vector_components:
                lit_bytes = bytearray(struct.pack(">f", float(component)))
                byte_code.extend(lit_bytes)
        continue
    # Handle generic commands
    else:
        print("Parsing generic command...")
        if word == "LIT":
            code_type = "lit_type"
        byte_code.append(instruction_opcodes[word])
        continue

pure_bytes = bytes(byte_code)
with open("Test.slb", "wb") as binary_file:
    binary_file.write(pure_bytes)
LIT, 
Parsing generic command...
FLT, lit_type
Parsing literal type...
-1.0, literal
Parsing literal value...
LIT, literal
Parsing literal value...
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_20464/1959865281.py in <module>
     23         # Handle float literals
     24         if lit_type == "FLT":
---> 25             lit_bytes = bytearray(struct.pack(">f", float(word)))
     26             byte_code.extend(lit_bytes)
     27         # Handle vector literals

ValueError: could not convert string to float: 'LIT'