6.0 KiB
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...
[1;31m---------------------------------------------------------------------------[0m [1;31mValueError[0m Traceback (most recent call last) [1;32m~\AppData\Local\Temp/ipykernel_20464/1959865281.py[0m in [0;36m<module>[1;34m[0m [0;32m 23[0m [1;31m# Handle float literals[0m[1;33m[0m[1;33m[0m[1;33m[0m[0m [0;32m 24[0m [1;32mif[0m [0mlit_type[0m [1;33m==[0m [1;34m"FLT"[0m[1;33m:[0m[1;33m[0m[1;33m[0m[0m [1;32m---> 25[1;33m [0mlit_bytes[0m [1;33m=[0m [0mbytearray[0m[1;33m([0m[0mstruct[0m[1;33m.[0m[0mpack[0m[1;33m([0m[1;34m">f"[0m[1;33m,[0m [0mfloat[0m[1;33m([0m[0mword[0m[1;33m)[0m[1;33m)[0m[1;33m)[0m[1;33m[0m[1;33m[0m[0m [0m[0;32m 26[0m [0mbyte_code[0m[1;33m.[0m[0mextend[0m[1;33m([0m[0mlit_bytes[0m[1;33m)[0m[1;33m[0m[1;33m[0m[0m [0;32m 27[0m [1;31m# Handle vector literals[0m[1;33m[0m[1;33m[0m[1;33m[0m[0m [1;31mValueError[0m: could not convert string to float: 'LIT'