-
Notifications
You must be signed in to change notification settings - Fork 0
/
converter.py
159 lines (134 loc) · 5.29 KB
/
converter.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
import os
import sys
from loguru import logger
from data import COMMANDS, LOG_LEVEL_SHORT_FORM, HANDLER_FORMAT
from messages import msg_cli_help
def hex_to_simple(hex_code: str) -> str:
"""
Convert hex to simple hex 00H representation.
"""
return hex_code[2:].upper() + "H"
def process_instruction_args(cmdname: str, cmdargs: tuple) -> tuple:
"""
Processes raw strings arguments of 8085 instruction and tokenize and process them
"""
processed_cmd_args = list(cmdargs)[:]
cmd_parameters = COMMANDS[cmdname]["parameters"]
# Every command's parameter is a dict of [p_name, p_type]
for (index, argument), p_name in zip(enumerate(cmdargs), cmd_parameters):
# both address and values are specified in simple hex (5533H, 05H) so process them
if p_name == "address" or p_name == "value":
logger.debug(f"Processing to hex for '{argument=}'")
hex_code = process_hex(argument)
if not hex_code:
return ()
processed_cmd_args[index] = hex_code
return tuple(processed_cmd_args)
def process_hex(argument: str) -> str:
"""
Convert simple to specify hex string to proper python hexadecimals
23H -> '0x23'
2300H -> '0x2300'
"""
hex_code = argument
# if the hex argument has H at last, skip the H
if argument[-1].lower() == "h":
hex_code = "0x" + argument[:-1]
else:
hex_code = "0x" + argument
# check if given hex code is valid by converting to int
# if error then its isn't hex and we raise invalid token
try:
int(hex_code, 16)
except ValueError:
logger.warning(f"hex valid check failed on {hex_code}")
logger.error(ValueError(f"Invalid token: Expected hex byte got '{argument}'"))
return ""
return hex_code
def process_comments(cmd_list: tuple) -> tuple:
"""
Iterates through the list and if ';' found discard ';' and all items after ';'
"""
logger.debug(f"Processing comments: Got {cmd_list}")
new_cmd_list = []
for token in cmd_list:
if token == ";":
logger.debug(f"Processed comments: {new_cmd_list}")
return tuple(new_cmd_list)
elif ";" in token:
# example case: MVI A 01H;comment -> split at ; and put first item to cmd and throw others
token_parts = token.split(";")
if token_parts[0].strip():
# for cases like 01H ;comments splitting at ; gives first item as ''
new_cmd_list.append(token_parts[0].strip())
logger.debug(f"Processed comments: {new_cmd_list}")
return tuple(new_cmd_list)
else:
new_cmd_list.append(token)
logger.debug(f"No comments found: {new_cmd_list}")
return tuple(new_cmd_list)
def process_c_mode_args(args: tuple) -> tuple:
cmd = " ".join(args)
cmds = [i.strip() for i in cmd.split(";")]
logger.debug(f"Running in cmd mode: commands {cmds}")
return tuple(cmds)
def process_file_mode_args(filename: str) -> tuple:
cmds = []
if not os.path.exists(filename):
logger.error(f"No file named {filename} found.")
with open(filename, "r") as rf:
# iterating on rf will yeield lines with \n at last
cmds = [line.strip() for line in rf]
logger.debug(f"Running in file mode: commands {cmds}")
return tuple(cmds)
def is_label(token: str) -> bool:
"""
Determine if a token is a label or not
Search for : tag basically and make sure it has >=1 letter
"""
if ":" not in token:
logger.debug(f"Label check: No labels found when evaluating '{token}'")
return False
if token.count(":") > 1:
logger.debug(f"Label check failed: contains multiple colons {token}")
return False
token_parts = [i for i in token.split(":")]
# when a proper label like (BACK:) is splitted the second item is always '' (prevents ':Back' or 'Bac:k')
if token_parts[1] != "":
logger.debug(
f"Label check failed: contains charecters '{token_parts[1]}' after colon(:) '{token}'"
)
return False
if not token_parts[0].strip():
logger.debug(f"Label check: Invalid label no charectars only colon '{token}")
return False
return True
def process_cmd_line_args(args: tuple, logger) -> tuple:
log_level = "WARNING"
indirect_mode = False
if args and args[0] == "-i":
indirect_mode = True
args = args[1:]
if len(args) > 1 and args[0] == "-v":
level = args[1]
log_level = LOG_LEVEL_SHORT_FORM.get(level, log_level)
args = args[2:]
logger.remove()
logger.add(sys.stderr, level=log_level, format=HANDLER_FORMAT)
logger.add("debug.log", level="DEBUG", rotation="1 MB")
logger.debug(f"Got cmd args {args}")
commands, file_db = tuple(), ""
if args and (args[0] == "help" or args[0] == "--help" or args[0] == "-h"):
msg_cli_help()
exit(0)
if len(args) > 1 and args[0] == "-db":
filename = args[1]
file_db = filename
args = args[2:]
if len(args) > 1 and args[0] == "-f":
commands = process_file_mode_args(args[1])
args = args[2:]
if len(args) > 1 and args[0] == "-c":
commands = process_c_mode_args(args[1:])
args = args[2:]
return (args, commands, file_db, indirect_mode)