0% found this document useful (0 votes)
4 views26 pages

Python Interrupter

The document describes a Python class named DirectExecVM that simulates a virtual machine for executing bytecode. It includes methods for initializing the VM, preprocessing code, loading programs, and executing various opcodes with detailed logging options. The VM supports operations like memory management, arithmetic calculations, and logical comparisons, while also handling program flow control.

Uploaded by

s231049
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views26 pages

Python Interrupter

The document describes a Python class named DirectExecVM that simulates a virtual machine for executing bytecode. It includes methods for initializing the VM, preprocessing code, loading programs, and executing various opcodes with detailed logging options. The VM supports operations like memory management, arithmetic calculations, and logical comparisons, while also handling program flow control.

Uploaded by

s231049
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

import math

import re
from datetime import datetime
import random
import sys
import time
import os

class DirectExecVM():
def __init__(self,parent=['unknown'],verbose=False):
[Link] = 1
[Link] = [0,0,0,0,0,0,0]
[Link] = [0]*100
[Link] = 0
[Link] = []
[Link] = [0,0] # in non-vm, lg has 4 items which 2 and 3 are reversed
for system use
[Link] = [0]*16
[Link] = False # Track if last logic comparison passed
[Link] = 0
if verbose: print(f"{self.get_formatted_time()} L [from {str(parent)}] ->
__init__: Loaded successfully.")
def increase_pointer(self,verbose=False,parent=['unknown']):
if verbose: print(f"{self.get_formatted_time()} L [from {str(parent)}] ->
increase_pointer: Set [Link] to {[Link]+1}")
[Link] += 1
def get_formatted_time(self):
return [Link]().strftime("%Y-%m-%d %H:%M:%S.%f")
def remove_comments(self,code,verbose=False,parent=['unknown']):
if verbose: print(f"{self.get_formatted_time()} L [from {str(parent)}] ->
remove_comments: Removing comments.")
return [Link](r'/\*.*?\*/','',code,flags=[Link])
def
preprocess(self,code,verbose=False,parent=['unknown'],rm_comment=True)
:
if verbose: print(f"{self.get_formatted_time()} L [from {str(parent)}] ->
preprocess: Preparing...")
clean = code
if rm_comment:
clean=self.remove_comments(clean,verbose,parent=parent)
# clean = [Link]('\x20','')
return clean
def loadprog(self,bytecode,verbose=False,parent=['unknown']):
# [Link] = [Link]()
[Link] = list(str(bytecode))
if verbose: print(f"{self.get_formatted_time()} L [from {str(parent)}] ->
loadprog: Loaded program to [Link]")
def
execute(self,verbose=False,parent=['unknown'],max=10**10,force_ping=0):
increase_pointer = self.increase_pointer
if verbose: print(f"{self.get_formatted_time()} L [from {str(parent)}] ->
execute:","Set pointer to 0")
[Link] = 0
[Link] = 0
self.force_ping = force_ping
[Link] = 0
[Link] = 0
increase_pointer = self.increase_pointer
while True:
# [Link](0.01)
# input("")
[Link] += 1
# for the ping, we use max of force_ping and [Link]
[Link](([Link] if self.force_ping < [Link] else
self.force_ping)/1000)
if [Link] >= len([Link]):
if verbose: print(f"\033[93m{self.get_formatted_time()} W [from
{str(parent)}] -> execute: Reached end of program without exit opcode,
exiting\033[0m")
break
elif [Link] > max:
if verbose: print(f"\033[93m{self.get_formatted_time()} W [from
{str(parent)}] -> execute: reached maximum opcode limit ({max}), exiting\
033[0m")
break
if verbose:
# i want to use gray color for this "verbose" type log
if verbose: print(f"\033[90m{self.get_formatted_time()} V [from
{str(parent)}] -> execute: pointer={hex([Link])}
state={hex([Link])} opcode={hex(ord([Link][[Link]]))}\033[0m")
if [Link] == 0:
# Reset lgpass flag if current opcode is not 'G' (lgelse)
if [Link][[Link]] != 'G':
[Link] = False
if [Link][[Link]] in ['\x20', '\t', '\n', '\r']: # whitespace
[Link] = 0
increase_pointer()
continue
elif [Link][[Link]] == '1': # init
[Link] = 0
if verbose: print(f"\033[90m{self.get_formatted_time()} V [from
{str(parent)}] -> execute: reset db\033[0m")
[Link] = [0,0,0,0,0,0,0]
if verbose: print(f"\033[90m{self.get_formatted_time()} V [from
{str(parent)}] -> execute: reset tmp\033[0m")
[Link] = [0]*100
increase_pointer()
continue
elif [Link][[Link]] == '2': # clmem
if verbose: print(f"\033[90m{self.get_formatted_time()} V [from
{str(parent)}] -> execute: reset db\033[0m")
[Link] = [0,0,0,0,0,0,0]
increase_pointer()
continue
elif [Link][[Link]] == '3': # mov
[Link] = 1
increase_pointer()
continue
elif [Link][[Link]] == '4': # section/lbl
for i in range(3): increase_pointer()
continue
elif [Link][[Link]] == '5': # inc/add
[Link] = 3
increase_pointer()
continue
elif [Link][[Link]] == '6': # turbo mode which doesn't
support in py
if [Link]+3 < len([Link]):
if verbose: print(f"{self.get_formatted_time()} W [from
{str(parent)}] -> execute: 0x36 (turbo) supports TurboWarp's DirectRunVM
only, ignoring.")
increase_pointer()
continue
elif [Link][[Link]] == '8': # cltmp - clear temp registers
[Link] = [0]*100
if verbose: print(f"\033[90m{self.get_formatted_time()} V [from
{str(parent)}] -> execute: reset tmp\033[0m")
increase_pointer()
continue
elif [Link][[Link]] == '9': # lgc - clear logic registers
[Link] = [0,0]
if verbose: print(f"\033[90m{self.get_formatted_time()} V [from
{str(parent)}] -> execute: reset lg\033[0m")
increase_pointer()
continue
elif [Link][[Link]] == 'm': # memory store (m)
[Link] = 7
increase_pointer()
continue
elif [Link][[Link]] == 'S': # exit
if verbose: print(f"\033[92m{self.get_formatted_time()} L [from
{str(parent)}] -> execute: safe exit\033[0m")
return 0 # break
elif [Link][[Link]] == 'c': # start of variable operation(s)
[Link] = 5
increase_pointer()
continue
elif [Link][[Link]] == '7': # goto
[Link] = 8
[Link] += 1
continue
elif [Link][[Link]] == 'q': # \x71, i guess q is right
[Link] = 4
increase_pointer()
continue
elif [Link][[Link]] == 'n': # copy temp to variable
[Link] = 9
[Link] += 1
continue
elif [Link][[Link]] == 'f': # lg
[Link] = 10
[Link] += 1
continue
elif [Link][[Link]] == 'g':
try: [Link][0] = float([Link][0])
except: pass
try: [Link][1] = float([Link][1])
except: pass
try: [Link][0] = str([Link][0])
except: pass
try: [Link][1] = str([Link][1])
except: pass
lgresult = ([Link][0] == [Link][1])
if verbose:
print(f'\033[90m{self.get_formatted_time()} V [from
{str(parent)}] -> execute: lg eq "{[Link][0]}" "{[Link][1]}" is {lgresult}')
if lgresult:
[Link] = True
[Link] = 8
increase_pointer()
else:
[Link] = False
# Skip 2-digit label
increase_pointer()
increase_pointer()
increase_pointer()
continue
elif [Link][[Link]] == '+':
# its short, no state needed
[Link][2] = [Link][0]+[Link][1]
increase_pointer()
continue
elif [Link][[Link]] == '-':
[Link][2] = [Link][0]-[Link][1]
increase_pointer()
continue
elif [Link][[Link]] == "*":
[Link][2] = [Link][0]*[Link][1]
increase_pointer()
continue
elif [Link][[Link]] == "/":
[Link][2] = [Link][0]/[Link][1]
increase_pointer()
continue
elif [Link][[Link]] == "^":
[Link][2] = [Link][0]**[Link][1]
increase_pointer()
continue
elif [Link][[Link]] == 'C': # C: tempXRoot (custom root)
[Link][2] = [Link][0]**(1/[Link][1])
increase_pointer()
continue
elif [Link][[Link]] == 'A': # sqrt
[Link][2] = [Link]([Link][0])
increase_pointer()
continue
elif [Link][[Link]] == 'B': # cbrt
[Link][2] = [Link]([Link][0])
increase_pointer()
continue
elif [Link][[Link]] == 'D': # log
[Link][2] = [Link]([Link][0])
increase_pointer()
continue
elif [Link][[Link]] == 'h': # lg neq (!=)
try: [Link][0] = float([Link][0])
except: pass
try: [Link][1] = float([Link][1])
except: pass
try: [Link][0] = str([Link][0])
except: pass
try: [Link][1] = str([Link][1])
except: pass
lgresult = ([Link][0] != [Link][1])
if verbose:
print(f'\033[90m{self.get_formatted_time()} V [from
{str(parent)}] -> execute: lg neq "{[Link][0]}" "{[Link][1]}" is {lgresult}')
if lgresult:
[Link] = True
[Link] = 8
increase_pointer()
else:
[Link] = False
# Skip 2-digit label
increase_pointer()
increase_pointer()
increase_pointer()
continue
elif [Link][[Link]] == 'i': # lg gtr (>)
try: [Link][0] = float([Link][0])
except: pass
try: [Link][1] = float([Link][1])
except: pass
lgresult = ([Link][0] > [Link][1])
if verbose:
print(f'\033[90m{self.get_formatted_time()} V [from
{str(parent)}] -> execute: lg gtr "{[Link][0]}" "{[Link][1]}" is {lgresult}')
if lgresult:
[Link] = True
[Link] = 8
increase_pointer()
else:
[Link] = False
# Skip 2-digit label
increase_pointer()
increase_pointer()
increase_pointer()
continue
elif [Link][[Link]] == 'j': # lg geq (>=)
try: [Link][0] = float([Link][0])
except: pass
try: [Link][1] = float([Link][1])
except: pass
lgresult = ([Link][0] >= [Link][1])
if verbose:
print(f'\033[90m{self.get_formatted_time()} V [from
{str(parent)}] -> execute: lg geq "{[Link][0]}" "{[Link][1]}" is {lgresult}')
if lgresult:
[Link] = True
[Link] = 8
increase_pointer()
else:
[Link] = False
# Skip 2-digit label
increase_pointer()
increase_pointer()
increase_pointer()
continue
elif [Link][[Link]] == 'k': # lg lss (<)
try: [Link][0] = float([Link][0])
except: pass
try: [Link][1] = float([Link][1])
except: pass
lgresult = ([Link][0] < [Link][1])
if verbose:
print(f'\033[90m{self.get_formatted_time()} V [from
{str(parent)}] -> execute: lg lss "{[Link][0]}" "{[Link][1]}" is {lgresult}')
if lgresult:
[Link] = True
[Link] = 8
increase_pointer()
else:
[Link] = False
# Skip 2-digit label
increase_pointer()
increase_pointer()
increase_pointer()
continue
elif [Link][[Link]] == 'l': # lg leq (<=)
try: [Link][0] = float([Link][0])
except: pass
try: [Link][1] = float([Link][1])
except: pass
lgresult = ([Link][0] <= [Link][1])
if verbose:
print(f'\033[90m{self.get_formatted_time()} V [from
{str(parent)}] -> execute: lg leq "{[Link][0]}" "{[Link][1]}" is {lgresult}')
if lgresult:
[Link] = True
[Link] = 8
increase_pointer()
else:
[Link] = False
# Skip 2-digit label
increase_pointer()
increase_pointer()
increase_pointer()
continue
elif [Link][[Link]] == 'R': # temp cmd and only this special
version have (Beta): RANDOM
if verbose:
print(f'\033[90m{self.get_formatted_time()} V [from
{str(parent)}] -> execute: random float 0-1 now in tmp3\033[0m')
[Link][2] = [Link]()
increase_pointer()
elif [Link][[Link]] == 'r':
try:[Link][2] =
[Link](int([Link][0]),int([Link][1]))
except:pass
increase_pointer()
if verbose:
print(f'\033[90m{self.get_formatted_time()} V [from
{str(parent)}] -> execute: random int between tmp1 ({[Link][0]}) and
tmp2 ({[Link][1]}) now in tmp3\033[0m')
elif [Link][[Link]] == 'G': # lgelse
if verbose:
print(f'\033[90m{self.get_formatted_time()} V [from
{str(parent)}] -> execute: lgelse (lgpass={[Link]})')
if not [Link]:
# Previous logic condition failed, execute else block (jump to
label)
[Link] = False
[Link] = 8 # goto
increase_pointer()
else:
# Previous logic condition passed, skip else block and its label
[Link] = False
increase_pointer()
increase_pointer()
increase_pointer()
continue

elif verbose:
print(f"\033[93m{self.get_formatted_time()} W [from
{str(parent)}] -> execute: Unknown opcode
{hex(ord([Link][[Link]]))} at {hex([Link])}\033[0m")
increase_pointer()
continue
elif [Link] == 1:
if [Link][[Link]] != 'c': [Link](2)
[Link] = 2
increase_pointer()
continue
elif [Link] == 2:
# WE DETECTED 3, WENT TO STATE 1, SAW 'c', NOW WE'RE IN
STATE 2!
# MUST BE c1-c7! IF NOT, GO HOME AND EAT ERRORS!!!!!!!
if not [Link][[Link]].isdigit():
[Link](3) # GO HOME AND EAT ERRORS!

var_index = int([Link][[Link]]) - 1
[Link] += 1

# MUST BE 1-7! IF NOT, GO HOME AND EAT ERRORS!!!!!!!


if var_index < 0 or var_index >= len([Link]):
[Link](3) # GO HOME AND EAT ERRORS!

# NOW a OR d OR c MUST BE NEXT! IF NOT, GO HOME AND EAT


ERRORS!!!!!!!
if [Link] >= len([Link]):
[Link](3) # GO HOME AND EAT ERRORS!

if [Link][[Link]] == 'c':
# -> I SAW "c" - REGISTER COPY (3c1c2 means c1 = c2)
[Link] += 1

if [Link] >= len([Link]) or not


[Link][[Link]].isdigit():
[Link](3) # GO HOME AND EAT ERRORS!

src_var_index = int([Link][[Link]]) - 1
[Link] += 1

# VALIDATE SOURCE REGISTER


if src_var_index < 0 or src_var_index >= len([Link]):
[Link](3) # GO HOME AND EAT ERRORS!

# COPY VALUE
v = float([Link][src_var_index])
if v == 0.0:
v = 0.0
[Link][var_index] = v
if verbose:
print(f"\033[90m{self.get_formatted_time()} V [from
{str(parent)}] -> execute: mov c{var_index + 1} = c{src_var_index + 1}
({[Link][var_index]}) (register copy)\033[0m")

[Link] = 0
continue

elif [Link][[Link]] == 'a':


# -> I SAW "a" - STRING ASSIGNMENT
[Link] += 1
string_buffer = []

# LET'S FIND b, BEFORE REACHING FILE END!


while [Link] < len([Link]) and [Link][[Link]] !=
'b':
if [Link][[Link]] == '\\':
[Link] += 1
if [Link] < len([Link]):
# handle escape sequences
escape_chars = {'a': 'a', 'b': 'b', 'd': 'd', 'e': 'e', '\\': '\\'}
char = [Link][[Link]]
string_buffer.append(escape_chars.get(char, char))
[Link] += 1
else:
string_buffer.append([Link][[Link]])
[Link] += 1

# IF WE REACH FILE END, THROW ERROR ON HIS FACE


if [Link] >= len([Link]) or [Link][[Link]] != 'b':
[Link](4) # THROW ERROR ON HIS FACE

[Link] += 1 # Skip 'b'

# FOUND b! ASSIGN TO REGISTER cX


try:
num_str = ''.join(string_buffer)
# normalize to float and remove negative-zero sign
[Link][var_index] = float(num_str)
if isinstance([Link][var_index], float) and [Link][var_index]
== 0.0:
[Link][var_index] = 0.0
if verbose:
print(f"\033[90m{self.get_formatted_time()} V [from
{str(parent)}] -> execute: mov c{var_index + 1} = {[Link][var_index]}
(string)\033[0m")
except ValueError:
[Link](9)

[Link] = 0
continue

elif [Link][[Link]] == 'd':


# -> I SAW "d" - NUMBER ASSIGNMENT
increase_pointer()
num_buffer = ''

# LET'S FIND e, BEFORE REACHING FILE END!


while [Link] < len([Link]) and [Link][[Link]] !=
'e':
num_buffer += [Link][[Link]]
[Link] += 1

# AND IF WE DO REACH THE END, GO TO HOME AND EAT


ERRORS
if [Link] >= len([Link]) or [Link][[Link]] != 'e':
[Link](8) # GO HOME AND EAT ERRORS

increase_pointer() # Skip 'e'

# FOUND e! ASSIGN TO REGISTER cX


try:
[Link][var_index] = float(num_buffer)
if isinstance([Link][var_index], float) and [Link][var_index]
== 0.0:
[Link][var_index] = 0.0
if verbose:
print(f"\033[90m{self.get_formatted_time()} V [from
{str(parent)}] -> execute: mov c{var_index + 1} = {[Link][var_index]}
(number)\033[0m")
except ValueError:
[Link](9)

[Link] = 0
continue

else:
# -> I SAW OTHER THINGS
[Link](3) # GO HOME AND EAT ERROR LA!!!!
elif [Link] == 3:
# format: 5{!c}{!p}{!d}{float}{!e}
# expect variable c1,c2,etc.
if [Link][[Link]] != 'c':
[Link](5)
increase_pointer()
# get variable index
if [Link] >= len([Link]) or not
[Link][[Link]].isdigit():
[Link](6)
[Link][0] = int([Link][[Link]])-1
increase_pointer()
# skip separator
if [Link] < len([Link]):
increase_pointer() # skip separator
# expect 'd' for float literal
if [Link] >= len([Link]) or [Link][[Link]] != 'd':
[Link](7)
increase_pointer()
# parse float between d and e
[Link][1] = ''
while [Link] < len([Link]) and [Link][[Link]] != 'e':
[Link][1] += [Link][[Link]]
increase_pointer()
if [Link] >= len([Link]) or [Link][[Link]] != 'e':
[Link](8)
increase_pointer()
try:
[Link][2] = float([Link][1])
newv = float([Link][[Link][0]]) + [Link][2]
# normalize negative zero
if isinstance(newv, float) and newv == 0.0:
newv = 0.0
[Link][[Link][0]] = newv
except ValueError:
[Link](9)
[Link] = 0
continue
elif [Link] == 4: # q - output
if verbose:
print(f"\033[90m{self.get_formatted_time()} V [from
{str(parent)}] -> execute: Processing output instruction\033[0m")

# Check what type of output we have


if [Link] >= len([Link]):
if verbose:
print(f"\033[91m{self.get_formatted_time()} E [from
{str(parent)}] -> execute: Unexpected end of program in output\033[0m")
[Link] = 0
continue

if [Link][[Link]] == 'a':
# STRING OUTPUT: qa...b
[Link] += 1
string_buffer = []

# Parse string between 'a' and 'b'


while [Link] < len([Link]) and [Link][[Link]] !=
'b':
if [Link][[Link]] == '\\':
# Handle escape sequences
[Link] += 1
if [Link] < len([Link]):
escape_chars = {
'a': 'a',
'b': 'b',
'd': 'd',
'e': 'e',
'\\': '\\',
'n': '\n',
't': '\t',
'r': '\r'
}
char = [Link][[Link]]
string_buffer.append(escape_chars.get(char, char))
[Link] += 1
else:
# Backslash at end of program
string_buffer.append('\\')
else:
string_buffer.append([Link][[Link]])
[Link] += 1

if [Link] >= len([Link]) or [Link][[Link]] != 'b':


if verbose:
print(f"\033[91m{self.get_formatted_time()} E [from
{str(parent)}] -> execute: Unterminated string in output\033[0m")
[Link] = 0
continue

[Link] += 1 # Skip 'b'


output_str = ''.join(string_buffer)
if verbose:
print(f"{self.get_formatted_time()} O [from {str(parent)}] ->
{output_str}")
else:
print(output_str)

elif [Link][[Link]] == 'd':


# FLOAT OUTPUT: qd...e
[Link] += 1
num_buffer = ''

# Parse number between 'd' and 'e'


while [Link] < len([Link]) and [Link][[Link]] !=
'e':
num_buffer += [Link][[Link]]
[Link] += 1

if [Link] >= len([Link]) or [Link][[Link]] != 'e':


if verbose:
print(f"\033[91m{self.get_formatted_time()} E [from
{str(parent)}] -> execute: Unterminated float in output\033[0m")
[Link] = 0
continue

[Link] += 1 # Skip 'e'

try:
float_value = float(num_buffer)
if verbose:
print(f"{self.get_formatted_time()} O [from {str(parent)}] -
> {float_value}")
else:
print(float_value)
except ValueError:
if verbose:
print(f"\033[91m{self.get_formatted_time()} E [from
{str(parent)}] -> execute: Invalid float format: {num_buffer}\033[0m")

elif [Link][[Link]] == 'c':


# VARIABLE OUTPUT: qc{1-7}
[Link] += 1

if [Link] >= len([Link]) or not


[Link][[Link]].isdigit():
if verbose:
print(f"\033[91m{self.get_formatted_time()} E [from
{str(parent)}] -> execute: Expected variable number after 'c' in output\
033[0m")
[Link] = 0
continue

var_index = int([Link][[Link]]) - 1
[Link] += 1

if 0 <= var_index < len([Link]):


value = [Link][var_index]
if verbose:
print(f"{self.get_formatted_time()} O [from {str(parent)}] -
> {value}")
else:
print(value)
else:
if verbose:
print(f"\033[91m{self.get_formatted_time()} E [from
{str(parent)}] -> execute: Invalid variable index c{var_index + 1}\033[0m")

else:
if verbose:
print(f"\033[91m{self.get_formatted_time()} E [from
{str(parent)}] -> execute: Invalid output type '{[Link][[Link]]}'
(expected 'a', 'd', or 'c')\033[0m")
# Skip to next valid instruction
while [Link] < len([Link]) and [Link][[Link]] != '\
x20':
[Link] += 1

[Link] = 0
continue
elif [Link] == 5:
if [Link][[Link]].isdigit():
[Link][0] = int([Link][[Link]]) - 1
increase_pointer()
if [Link] < len([Link]) and [Link][[Link]] == '?':
try:
[Link][1] = float(input(f"Value for
c{[Link][0]+1} \033[90m(Default: {[Link][[Link][0]]})\
033[0m: "))
except:
[Link](13)

[Link][[Link][0]] = [Link][1]
if verbose: print(f"\033[90m{self.get_formatted_time()} V
[from {str(parent)}] -> execute: assign input \"\
033[1;90m{[Link][1]}\033[0;90m\" to register db
{hex([Link][0])}")
increase_pointer()
else:
# its part of another operation, variable index alreay in
reserved[0]
# dont reset state yet- let next opcoe hanle it.
pass
[Link] = 0
continue
else:
[Link](11)
elif [Link] == 6:
if verbose: print(f"\033[92m{self.get_formatted_time()} W [from
{str(parent)}] -> execute: deprecated state 6\033[0m")
# and what do we do now? should we increase pointer and
continue? idk
[Link] = 0
increase_pointer()
continue
elif [Link] == 7:
if verbose: print(f"\033[90m{self.get_formatted_time()} V [from
{str(parent)}] -> execute: process memory operation\033[0m")

if [Link][[Link]] == 'c':
# mc... patterns - VARIABLE OPERATIONS
[Link] += 1
if [Link] < len([Link]) and [Link][[Link]].isdigit():
var_index = int([Link][[Link]])-1 # var index
# the bug: t0+t1 -> t2 in binary, i guess it become [:-1] and
[0] to [1]
[Link] += 1
if [Link] < len([Link]) and [Link][[Link]] ==
'p':
# m - copy var to tmp register
[Link] += 1
if [Link]+1 < len([Link]) and
[Link][[Link]].isdigit() and [Link][[Link]+1].isdigit():
# get tmp reg id
tmp_index = int([Link][[Link]]
+[Link][[Link]+1])
[Link] += 2
# tmp_index in bytecode is 1-based and must not be 00
if tmp_index == 0:
if verbose:
print(f"\033[91m{self.get_formatted_time()} E
[from {str(parent)}] -> execute: Invalid tmp id 00 in mcp c{var_index+1}\
033[0m")
[Link](12)
# Convert 1-based tmp index from bytecode to 0-based
internal index
tmp_index = tmp_index - 1
if 0 <= var_index < len([Link]) and 0 <= tmp_index <
len([Link]):
if verbose:
print(f"{self.get_formatted_time()} D [from
{str(parent)}] -> mcp PRE tmp[0:8]={[Link][0:8]}
db[0:8]={[Link][0:8]}")
# normalize value copied from db to tmp (remove
negative zero)
v = float([Link][var_index])
if v == 0.0:
v = 0.0
[Link][tmp_index] = v
if verbose:
print(f"\033[90m{self.get_formatted_time()} V
[from {str(parent)}] -> execute: mcp c{var_index+1} -> t{tmp_index} =
{v}\033[0m")
print(f"{self.get_formatted_time()} D [from
{str(parent)}] -> mcp POST tmp[0:8]={[Link][0:8]}
db[0:8]={[Link][0:8]}")
else:
if verbose:
print(f"\033[91m{self.get_formatted_time()} E
[from {str(parent)}] -> execute: invalid reg indices c{var_index+1} or
tmp[{tmp_index}]\033[0m")
[Link](12)
[Link] = 0
continue
elif [Link] < len([Link]) and [Link][[Link]] ==
'a':
# m - copy autotype (str/float) to var
[Link] += 1
string_buffer = []
# parse string between a and b
while [Link] < len([Link]) and
[Link][[Link]] != 'b':
if [Link][[Link]] == '\\':
[Link] += 1
if [Link] < len([Link]):
escape_chars = {'a': 'a', 'b': 'b', 'd': 'd', 'e': 'e', '\\':
'\\'}
char = [Link][[Link]]
string_buffer.append(escape_chars.get(char, char))
[Link] += 1
else:
string_buffer.append([Link][[Link]])
[Link] += 1
if [Link] >= len([Link]) or [Link][[Link]] !=
'b':
if verbose:
print(f"\033[91m{self.get_formatted_time()} E [from
{str(parent)}] -> execute: unterminated string literal in mca\033[0m")
[Link](4)
[Link] += 1
try:
num_str = ''.join(string_buffer)
v = float(num_str)
if v == 0.0:
v = 0.0
[Link][var_index] = v
if verbose:
print(f"\033[90m{self.get_formatted_time()} V [from
{str(parent)}] -> execute: mca c{var_index + 1} = {[Link][var_index]}\
033[0m")
except ValueError:
if verbose:
print(f"\033[91m{self.get_formatted_time()} E [from
{str(parent)}] -> execute: Invalid number format: {''.join(string_buffer)}\
033[0m")
[Link] = 0
continue
elif [Link] < len([Link]) and [Link][[Link]] ==
'd':
# n (cp tmpX varX) - copy float literal to variable
[Link] += 1
num_buffer = '' # Number buffer

# Parse number between 'd' and 'e'


while [Link] < len([Link]) and
[Link][[Link]] != 'e':
num_buffer += [Link][[Link]]
[Link] += 1

if [Link] >= len([Link]) or [Link][[Link]] !=


'e':
if verbose:
print(f"\033[91m{self.get_formatted_time()} E [from
{str(parent)}] -> execute: Unterminated number in mcd operation\033[0m")
[Link](8)

[Link] += 1 # Skip 'e'

# Convert to float and store


try:
v = float(num_buffer)
if v == 0.0:
v = 0.0
[Link][var_index] = v
if verbose:
print(f"\033[90m{self.get_formatted_time()} V [from
{str(parent)}] -> execute: mcd c{var_index + 1} = {[Link][var_index]}\
033[0m")
except ValueError:
if verbose:
print(f"\033[91m{self.get_formatted_time()} E [from
{str(parent)}] -> execute: Invalid number: {num_buffer}\033[0m")

[Link] = 0
continue

else:
if verbose:
print(f"\033[91m{self.get_formatted_time()} E [from
{str(parent)}] -> execute: Unknown memory operation after c{var_index +
1}\033[0m")
[Link](3)
else:
if verbose:
print(f"\033[91m{self.get_formatted_time()} E [from
{str(parent)}] -> execute: Expected variable number after 'c'\033[0m")
[Link](3)
continue

elif [Link][[Link]] == 'd':


# md... patterns - DIRECT FLOAT LITERAL TO TEMP REGISTER
[Link] += 1

# Parse float between 'd' and 'e'


num_buffer = ''
while [Link] < len([Link]) and [Link][[Link]] !=
'e':
num_buffer += [Link][[Link]]
[Link] += 1

if [Link] >= len([Link]) or [Link][[Link]] != 'e':


if verbose:
print(f"\033[91m{self.get_formatted_time()} E [from
{str(parent)}] -> execute: Unterminated float literal in md operation\
033[0m")
[Link](8)

[Link] += 1 # Skip 'e'

# Now expect 'p' and destination


if [Link] < len([Link]) and [Link][[Link]] == 'p':
[Link] += 1
if [Link] + 1 < len([Link]) and
[Link][[Link]].isdigit() and [Link][[Link] + 1].isdigit():
dest_index = int([Link][[Link]] +
[Link][[Link] + 1])
[Link] += 2
# dest_index must not be 00
if dest_index == 0:
if verbose:
print(f"\033[91m{self.get_formatted_time()} E [from
{str(parent)}] -> execute: Invalid tmp id 00 in md operation\033[0m")
[Link](12)
# convert 1-based dest index to 0-based
dest_index = dest_index - 1
try:
value = float(num_buffer)
# normalize negative zero
if value == 0.0:
value = 0.0
if 0 <= dest_index < len([Link]):
if verbose:
print(f"{self.get_formatted_time()} D [from
{str(parent)}] -> md PRE tmp[0:8]={[Link][0:8]} db[0:8]={[Link][0:8]}")
[Link][dest_index] = value
if verbose:
print(f"\033[90m{self.get_formatted_time()} V
[from {str(parent)}] -> execute: md{num_buffer}ep{dest_index+1:02d} ->
tmp[{dest_index}] = {value}\033[0m")
print(f"{self.get_formatted_time()} D [from
{str(parent)}] -> md POST tmp[0:8]={[Link][0:8]}
db[0:8]={[Link][0:8]}")
else:
if verbose:
print(f"\033[91m{self.get_formatted_time()} E
[from {str(parent)}] -> execute: Invalid tmp index {dest_index+1}\033[0m")
except ValueError:
if verbose:
print(f"\033[91m{self.get_formatted_time()} E [from
{str(parent)}] -> execute: Invalid float: {num_buffer}\033[0m")

[Link] = 0
else:
if verbose:
print(f"\033[91m{self.get_formatted_time()} E [from
{str(parent)}] -> execute: Expected 'c' or 'd' for memory operation\033[0m")
[Link](3)
continue
elif [Link] == 8: # goto (g)
if verbose:
print(f"\033[90m{self.get_formatted_time()} V [from
{str(parent)}] -> execute: find and goto point\033[0m")

# Format: g{label_id}
if [Link] + 1 < len([Link]) and
[Link][[Link]].isdigit() and [Link][[Link] + 1].isdigit():
# Get 2-digit label ID (01-99)
label_id = int([Link][[Link]] + [Link][[Link] + 1])
[Link] += 2

if verbose:
print(f"\033[90m{self.get_formatted_time()} V [from
{str(parent)}] -> execute: goto label {label_id:02d}\033[0m")

# Search for the label in the program - LABELS ARE 4{xx}


FORMAT!
label_found = False
search_pointer = 0

while search_pointer < len([Link]):


# Look for label format: 4{label_id}
if (search_pointer + 2 < len([Link]) and
[Link][search_pointer] == '4' and
[Link][search_pointer + 1].isdigit() and
[Link][search_pointer + 2].isdigit() and
int([Link][search_pointer + 1] + [Link][search_pointer
+ 2]) == label_id):

# Found the label! Jump to this position


[Link] = search_pointer
label_found = True
if verbose:
print(f"\033[90m{self.get_formatted_time()} V [from
{str(parent)}] -> execute: jumped to label {label_id:02d} at position
{hex(search_pointer)}\033[0m")
break

search_pointer += 1

if not label_found:
if verbose:
print(f"\033[91m{self.get_formatted_time()} E [from
{str(parent)}] -> execute: Label {label_id:02d} not found!\033[0m")
[Link](14)

else:
if verbose:
print(f"\033[91m{self.get_formatted_time()} E [from
{str(parent)}] -> execute: Invalid goto format\033[0m")
[Link](3)

[Link] = 0
continue
elif [Link] == 9: # n - copy temp to variable
if verbose:
print(f"\033[90m{self.get_formatted_time()} V [from
{str(parent)}] -> execute: copy temp to variable\033[0m")

# Format: n{tmp_id}p{c{var_id}}
if [Link] + 1 < len([Link]) and
[Link][[Link]].isdigit() and [Link][[Link] + 1].isdigit():

tmp_index = int([Link][[Link]] + [Link][[Link] +


1])
[Link] += 2
# tmp_index must not be 00
if tmp_index == 0:
if verbose:
print(f"\033[91m{self.get_formatted_time()} E [from
{str(parent)}] -> execute: Invalid tmp id 00 in n operation\033[0m")
[Link](12)
# convert 1-based tmp index to 0-based
tmp_index = tmp_index - 1

if [Link] < len([Link]) and [Link][[Link]] == 'p':


[Link] += 1
if [Link] + 1 < len([Link]) and [Link][[Link]]
== 'c' and [Link][[Link] + 1].isdigit():
var_index = int([Link][[Link] + 1]) - 1
[Link] += 2

if 0 <= tmp_index < len([Link]) and 0 <= var_index <


len([Link]):
if verbose:
print(f"{self.get_formatted_time()} D [from
{str(parent)}] -> n PRE tmp[0:8]={[Link][0:8]} db[0:8]={[Link][0:8]}")
v = float([Link][tmp_index])
if v == 0.0:
v = 0.0
[Link][var_index] = v
if verbose:
print(f"\033[90m{self.get_formatted_time()} V [from
{str(parent)}] -> execute: n{tmp_index+1:02d}pc{var_index + 1} ->
c{var_index + 1} = {[Link][tmp_index]}\033[0m")
print(f"{self.get_formatted_time()} D [from
{str(parent)}] -> n POST tmp[0:8]={[Link][0:8]} db[0:8]={[Link][0:8]}")
else:
if verbose:
print(f"\033[91m{self.get_formatted_time()} E [from
{str(parent)}] -> execute: Invalid register indices\033[0m")
[Link] = 0
continue
elif [Link] == 10:
# # elif [Link] == 10: # lgStore_V2 operation
if verbose:
print(f"\033[90m{self.get_formatted_time()} V [from
{str(parent)}] -> execute: Processing lgStore_V2\033[0m")

# PARSE FIRST VALUE ($1)


value1 = 0
if [Link] < len([Link]) and [Link][[Link]] == 'a':
# !a…!b FORMAT
[Link] += 1
value_buffer = []
while [Link] < len([Link]) and [Link][[Link]] !=
'b':
if [Link][[Link]] == '\\':
[Link] += 1
if [Link] < len([Link]):
escape_chars = {'a': 'a', 'b': 'b', 'd': 'd', 'e': 'e', '\\': '\\'}
char = [Link][[Link]]
value_buffer.append(escape_chars.get(char, char))
[Link] += 1
else:
value_buffer.append([Link][[Link]])
[Link] += 1

if [Link] >= len([Link]) or [Link][[Link]] != 'b':


[Link](4)

[Link] += 1
value1 = float(''.join(value_buffer))

elif [Link] < len([Link]) and [Link][[Link]] == 'd':


# !d…!e FORMAT
[Link] += 1
value_buffer = ''
while [Link] < len([Link]) and [Link][[Link]] !=
'e':
value_buffer += [Link][[Link]]
[Link] += 1

if [Link] >= len([Link]) or [Link][[Link]] != 'e':


[Link](4)

[Link] += 1
value1 = float(value_buffer)

elif [Link] < len([Link]) and [Link][[Link]] == 'c':


# c* FORMAT (VARIABLE)
[Link] += 1
if [Link] < len([Link]) and [Link][[Link]].isdigit():
var_index = int([Link][[Link]]) - 1
[Link] += 1
if 0 <= var_index < len([Link]):
value1 = [Link][var_index]
else:
[Link](3)
else:
[Link](3)
else:
[Link](3)

# EXPECT 'p' SEPARATOR


if [Link] >= len([Link]) or [Link][[Link]] != 'p':
[Link](3)
[Link] += 1 # Skip 'p'

# PARSE SECOND VALUE ($2) - SAME LOGIC AS ABOVE


value2 = 0
if [Link] < len([Link]) and [Link][[Link]] == 'a':
# !a…!b FORMAT
[Link] += 1
value_buffer = []
while [Link] < len([Link]) and [Link][[Link]] !=
'b':
if [Link][[Link]] == '\\':
[Link] += 1
if [Link] < len([Link]):
escape_chars = {'a': 'a', 'b': 'b', 'd': 'd', 'e': 'e', '\\': '\\'}
char = [Link][[Link]]
value_buffer.append(escape_chars.get(char, char))
[Link] += 1
else:
value_buffer.append([Link][[Link]])
[Link] += 1

if [Link] >= len([Link]) or [Link][[Link]] != 'b':


[Link](4)

[Link] += 1
value2 = float(''.join(value_buffer))

elif [Link] < len([Link]) and [Link][[Link]] == 'd':


# !d…!e FORMAT
[Link] += 1
value_buffer = ''
while [Link] < len([Link]) and [Link][[Link]] !=
'e':
value_buffer += [Link][[Link]]
[Link] += 1

if [Link] >= len([Link]) or [Link][[Link]] != 'e':


[Link](4)

[Link] += 1
value2 = float(value_buffer)

elif [Link] < len([Link]) and [Link][[Link]] == 'c':


# c* FORMAT (VARIABLE)
[Link] += 1
if [Link] < len([Link]) and [Link][[Link]].isdigit():
var_index = int([Link][[Link]]) - 1
[Link] += 1
if 0 <= var_index < len([Link]):
value2 = [Link][var_index]
else:
[Link](3)
else:
[Link](3)
else:
[Link](3)

# STORE BOTH VALUES IN lg[0] AND lg[1]


[Link][0] = value1
[Link][1] = value2

if verbose:
print(f"\033[90m{self.get_formatted_time()} V [from
{str(parent)}] -> execute: lgStore_V2 -> lg[0] = {[Link][0]}, lg[1] =
{[Link][1]}\033[0m")

[Link] = 0
continue
elif [Link] == 11:
pass
elif verbose:
print(f"\033[91m{self.get_formatted_time()} E [from {str(parent)}]
-> execute: CRITICAL: Invalid state {hex([Link])}\033[0m")
[Link](10)
continue
#
<program><config>[Link]="addition";[Link]=0</config><data>c1?
c2? mc1p01 mc2p02 + n03pc1 qc1 S</data></program>

You might also like