-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
96 lines (69 loc) · 2.64 KB
/
main.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
from colorama import init, Fore
from gwcc import il
from gwcc.backend.util import BackendError
init()
from pycparser import c_parser, preprocess_file, CParser
import gwcc
import platform
import argparse
from os import path
from gwcc.c_frontend import ParseError
def banner():
print 'The Gangweed Retargetable C Compiler [Version %s]' % (gwcc.__version__,)
print '(c) 2019 gangweed ganggang. All rights reserved.'
print
def parse_file_text(filename, use_cpp=False, cpp_path='cpp', cpp_args=''):
with open(filename) as f:
raw_text = f.read()
if use_cpp:
text = preprocess_file(filename, cpp_path, cpp_args)
else:
text = raw_text
return raw_text, CParser().parse(text, filename)
def print_error(err):
assert type(err) == ParseError or type(err) == BackendError
if hasattr(err, 'coord') and err.coord:
print e.coord
print source_code.split('\n')[e.coord.line - 1]
print ' ' * (e.coord.column - 1) + '^'
print Fore.RED + 'ERROR: ' + Fore.RESET + e.message
if __name__ == '__main__':
banner()
args_parser = argparse.ArgumentParser()
args_parser.add_argument('source_file', default='testcases/1.c', nargs='?')
args_parser.add_argument('-o', '--output', nargs=1)
args_parser.add_argument('-g', '--symbols', action='store_true', default=True)
args_parser.add_argument('--gen-dot', action='store_true')
args = args_parser.parse_args()
if args.output is None:
args.output = path.splitext(path.basename(args.source_file))[0] + '.asm'
parser = c_parser.CParser()
if platform.system() == 'Darwin':
source_code, ast = parse_file_text(args.source_file, use_cpp=True, cpp_path='clang', cpp_args='-E')
else:
source_code, ast = parse_file_text(args.source_file, use_cpp=True)
frontend = gwcc.Frontend(gwcc.abi.LC3)
try:
frontend.compile(ast)
except ParseError as e:
print_error(e)
exit(1)
if args.gen_dot:
for global_var in frontend._globals:
if type(global_var.value) == il.Function:
func = global_var.value
print func.pretty_print()
with open('tmp_cfg_func_%s.dot' % func.name, 'w') as f:
func.dump_graph(fd=f)
backend = gwcc.backend.LC3(frontend.get_globals(), with_symbols=args.symbols)
try:
backend.compile()
except BackendError as e:
print_error(e)
exit(1)
print '\n\n\n\n\n'
print '\n'.join(backend.get_output())
with open(args.output, 'w') as f:
f.write('\n'.join(backend.get_output()))
import os
os.system('scp ' + args.output + ' vm:complx')