52 lines
1.4 KiB
Python
52 lines
1.4 KiB
Python
import sys
|
|
import os
|
|
|
|
def rem_empty(data):
|
|
return [v for v in data if v]
|
|
|
|
class PreprocessorError(ValueError):
|
|
pass
|
|
|
|
def open_and_preprocess(path, name, main=False):
|
|
file = open(f"{path}/{name}", "r")
|
|
content = file.read()
|
|
defines = dict()
|
|
|
|
#take care of whitespaces
|
|
content_rem = rem_empty(content.split("\n"))
|
|
content = []
|
|
for line in content_rem:
|
|
content += [line.strip()]
|
|
|
|
#preprocessing
|
|
for line in content:
|
|
if line[0] == "#": #is process command
|
|
line_argv = rem_empty(line[1:].split(" "))
|
|
command = line_argv[0].lower()
|
|
if command == "name":
|
|
if main:
|
|
global out_name
|
|
out_name = line_argv[1]
|
|
elif command == "include":
|
|
open_and_preprocess(path, " ".join(line_argv[1:]))
|
|
elif command == "define":
|
|
defines[line_argv[1]] = " ".join(line_argv[2:])
|
|
else:
|
|
raise PreprocessorError(f"{command} preprocessor unknown")
|
|
else:
|
|
print(line)
|
|
|
|
temp = open(".temp", "w")
|
|
stdout = sys.stdout
|
|
sys.stdout = temp
|
|
path = "."
|
|
name = "main.bc"
|
|
out_name = None
|
|
open_and_preprocess(path, name, main=True)
|
|
sys.stdout = stdout
|
|
temp.close()
|
|
if not out_name:
|
|
raise PreprocessorError("#name <name> preprocessor missing")
|
|
else:
|
|
os.replace(".temp", f"{out_name}.txt")
|