-
Notifications
You must be signed in to change notification settings - Fork 0
/
champai.py
70 lines (51 loc) · 1.85 KB
/
champai.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
# champai.py
import argparse
from chailex import ChaiLex
from chaiparse import ChaiParse
from chaistat import ChaiStat
from chaispeed import ChaiSpeed
def parse_arguments():
"""
Parses the arguments given by the user.
:return: parsed arguments from stdin
"""
parser = argparse.ArgumentParser(description='Champai GLang Compiler')
parser.add_argument(
'input_file',
help='.imp file containing code in GLang'
)
parser.add_argument(
'--out',
default="a.o",
help='output the result of compilation to file'
)
return parser.parse_args()
def perform_compilation(input_file, output_file):
"""
Performs the compilation of given input file.
:return:
"""
lexer = ChaiLex()
parser = ChaiParse()
with open(input_file, 'r') as file:
code = file.read()
try:
tree = parser.parse(lexer.tokenize(code))
optimizer = ChaiSpeed(global_variables=parser.global_variables,
memory_indexes=parser.memory_indexes, next_free_memory_index=parser.next_free_memory_index)
optimizer.optimize_memory_allocations(parse_tree=tree[1])
manager = ChaiStat(parse_tree=tree, global_variables=optimizer.global_variables,
memory_indexes=optimizer.memory_indexes,
next_free_memory_index=optimizer.next_free_memory_index)
assembly_code = manager.compile()
with open(output_file, 'w') as file:
file.write(assembly_code)
print("champai: compilation succeeded!")
except Exception as e:
print("An error has occured during the compilation of '{}'\n{}".format(input_file, e))
exit(1)
def main():
arguments = parse_arguments()
perform_compilation(arguments.input_file, arguments.out)
if __name__ == "__main__":
main()