comparison python/zcc.py @ 106:f2d980eef509

improved code generation
author Windel Bouwman
date Mon, 31 Dec 2012 18:26:56 +0100
parents 6a303f835c6d
children 1544e7a4aa98
comparison
equal deleted inserted replaced
105:6a303f835c6d 106:f2d980eef509
1 #!/usr/bin/python 1 #!/usr/bin/python
2 2
3 import sys, os, argparse 3 import sys, os, argparse
4 from ppci import core 4 from ppci import core, frontends
5 5
6 parser = argparse.ArgumentParser(description='K# to bitcode compiler') 6 parser = argparse.ArgumentParser(description='K# to bitcode compiler')
7 parser.add_argument('source', type=str, help='the source file to build') 7 parser.add_argument('source', type=str, help='the source file to build')
8 args = parser.parse_args() 8 args = parser.parse_args()
9 9
11 with open(args.source, 'r') as f: 11 with open(args.source, 'r') as f:
12 src = f.read() 12 src = f.read()
13 except IOError: 13 except IOError:
14 print('Failed to load {0}'.format(args.source)) 14 print('Failed to load {0}'.format(args.source))
15 sys.exit(1) 15 sys.exit(1)
16 16 print('stage 1: Parsing')
17 # Create a context and a frontend: 17 # Create a context and a frontend:
18 context = core.Context() 18 context = core.Context()
19 frontend = core.frontends.ks.KsFrontend(context) 19 frontend = frontends.KsFrontend(context)
20 try: 20 try:
21 module = frontend.compilesource(src) 21 module = frontend.compilesource(src)
22 except core.CompilerException as e: 22 except core.CompilerException as e:
23 print(e) 23 print(e)
24 sys.exit(2) 24 lines = src.split(os.linesep)
25 row = e.row
26 col = e.col
27 line = lines[row - 1]
28 print('{0}:{1}'.format(row, line))
29 print(' ' * col + '^')
30 raise
31 #sys.exit(2)
25 32
26 # optionally run passes here: 33 # optionally run passes here:
27 # TODO 34 # TODO
35
36 print('stage 3: Code generation')
37 asmWriter = core.AsmWriter()
38 asmWriter.printModule(module)
28 39
29 # Generate code: 40 # Generate code:
30 bitcodeWriter = core.BitcodeWriter() 41 bitcodeWriter = core.BitcodeWriter()
31 with open(args.source + '.bc', 'wb') as f: 42 with open(args.source + '.bc', 'wb') as f:
32 bitcodeWriter.WriteModuleToFile(module, f) 43 bitcodeWriter.WriteModuleToFile(module, f)