Skip to content

Instantly share code, notes, and snippets.

@rodnaxel
Created February 25, 2020 04:01
Show Gist options
  • Save rodnaxel/482dbc80f4188e8b40af7b1dd908b883 to your computer and use it in GitHub Desktop.
Save rodnaxel/482dbc80f4188e8b40af7b1dd908b883 to your computer and use it in GitHub Desktop.
import argparse
import re
INDENT = 4 * " "
pattern = r"(?P<label>\w+:)?(?P<code>[^;]*)?;?(?P<comment>.*)?"
def parse_label(line: str) -> str:
if not line:
return ''
return line.upper() + '\n'
def parse_comments(line: str) -> str:
if not line:
return line
return f"; {line.lower().capitalize()}"
def parse_code(line: str) -> str:
if not line:
return line
tokens = [token.upper() for token in re.split(r"\s+|,", line) if token]
if "EQU" in tokens:
line = INDENT + '{:9}{:7}{:4}'.format(*tokens)
elif "$" in tokens[0]:
line = line.lower()
elif len(tokens) < 2:
tokens[0].upper()
line = INDENT + INDENT.join(tokens)
else:
command = tokens[0].upper()
operands = ", ".join(tokens[1:])
line = INDENT + '{0:6}{1}'.format(command, operands)
return line
def parse(line: str) -> str:
line = line.strip()
tokens = re.search(pattern, line).groupdict()
for key in tokens:
if tokens[key]:
tokens[key] = tokens[key].strip()
if not any(tokens.values()):
return line
label_s = parse_label(tokens['label'])
code_s = parse_code(tokens['code'])
comment_s = parse_comments(tokens['comment'])
line = '{}{}{}'.format(label_s, code_s, comment_s)
return line
class Formatter:
pattern = r"(?P<label>\w+:)?(?P<code>[^;]*)?;?(?P<comment>.*)?"
def __init__(self, source, dest):
self.source = source
self.dest = dest
self.debug_counter_line = 0
def format(self):
with open(self.source, encoding='utf-8') as fin:
with open(self.dest, "w", encoding='utf-8') as fout:
for line in fin:
line = parse(line)
print(line, file=fout)
self.debug_counter_line += 1
def report(self):
print("Source: {0}\nDest: {1}\nHandle line: {2}".format(
self.source, self.dest, self.debug_counter_line))
if __name__ == "__main__":
source = "KF2IND.asm"
dest = "output.asm"
p = argparse.ArgumentParser(description="Format asm 8051")
p.add_argument('-s', action='store', dest='source', default=source)
p.add_argument('-o', '--output', action='store', dest='output', default=dest)
p.add_argument('-с', '--config', action='store', dest='config')
args = p.parse_args()
formatter = Formatter(args.source, args.output)
formatter.format()
formatter.report()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment