Created
May 29, 2023 16:33
-
-
Save tur11ng/61f66e9c482d0553bcf26b1fb5230021 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from sys import argv | |
import re | |
use = """ | |
python3 mipsstacksaver.py [OPTION] filename | |
OPTIONS: | |
-m: merges the output to the input file | |
-s: prints the output to the standard output | |
Example use in source file: | |
myroutine: | |
# this is a comment | |
##save ra,s0,s1,s2,s3 | |
$addi $s1, $zero, 0 | |
$addi $s2, $zero, 0 | |
$move $s3, $zero | |
$move $s4, $zero | |
##load 1,2,3,4 | |
# BE CAREFUL! The order of registers after the "load" | |
# must be the same as the order of registers | |
# after the "save" | |
This program is intented for use with MIPS32/MIPS64 architecture. | |
""" | |
outmode = "" | |
def substitute(filename): | |
file = open(filename, "r+") | |
newfile = [] | |
for line in file: | |
if (re.fullmatch(r"\s*##((load)|(save)) (\w\w,)*(\w\w)\s*", line[:-1])): | |
line = line.rstrip() | |
leading = re.match(r"^\s*##", line).regs[0][1] | |
rest = line[leading-2:] | |
leading = line[:leading-2] | |
args = re.split(" ", line[2:]) | |
regs = re.split(",", args[1]) | |
if args[0] == "save": | |
newfile.append("{}addi $sp, $sp, -{}\n".format(leading, len(regs)*4)) | |
for i in range(0, len(regs)*4, 4): | |
newfile.append("{}sw ${}, {}($sp)\n".format(leading, regs[int(i/4)], i)) | |
else: | |
for i in range(0, len(regs)*4, 4): | |
newfile.append("{}lw ${}, {}($sp)\n".format(leading, regs[int(i/4)], i)) | |
newfile.append("{}addi $sp, $sp, {}\n". format(leading, len(regs)*4)) | |
else: | |
newfile.append(line) | |
global outmode | |
if outmode == "-s": | |
for i in newfile: | |
print(i) | |
elif outmode == "-m": | |
file.seek(0, 0) | |
file.writelines(newfile) | |
else: | |
print_use() | |
file.close() # also flushed the buffer | |
def print_use(): | |
print(use) | |
if __name__ == "__main__": | |
if len(argv) >= 3: | |
outmode = argv[1] | |
substitute(argv[2]) | |
else: | |
print_use() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment