-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompiler.py
More file actions
executable file
·79 lines (70 loc) · 2.24 KB
/
compiler.py
File metadata and controls
executable file
·79 lines (70 loc) · 2.24 KB
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
#!env python2.7
import model
import transpiler
import tempfile
import subprocess
import os
import error
if os.name == 'nt':
EXT = '.exe'
else:
EXT = ''
def compile(src, dst):
p = subprocess.Popen(['gcc' + EXT, src, '-o', dst, '-I.'], stderr=subprocess.PIPE)
out, err = p.communicate()
if p.returncode != 0:
raise error.CompilerError(err)
def run_c(src, prefix=''):
fd, binary = tempfile.mkstemp(prefix=prefix + '_', suffix='_compiled' + EXT)
try:
os.close(fd)
compile(src, binary)
p = subprocess.Popen([binary], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
if p.returncode < 0:
raise error.BinaryExecutionError((p.returncode, out, err))
return p.returncode, out, err
finally:
if os.path.exists(binary):
os.remove(binary)
def run_model(m, prefix=''):
transpiled = transpiler.transpile_model(m)
fd, cpath = tempfile.mkstemp(prefix=prefix + '_', suffix='_transpiled.c')
try:
with os.fdopen(fd, 'w') as f:
f.write(transpiled)
return run_c(cpath)
finally:
if os.path.exists(cpath):
os.remove(cpath)
if __name__ == '__main__':
import sys
import logging
logging.basicConfig(level=logging.DEBUG)
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('path')
parser.add_argument('-o', '--output')
parser.add_argument('--debug', action='store_true')
args = parser.parse_args()
content = open(args.path).read()
prefix = os.path.basename(args.path)
m = model.build_model(content)
transpiled = transpiler.transpile_model(m)
if args.debug:
for idx, line in enumerate(transpiled.splitlines()):
print '%s\t%s' % (idx+1, line)
cfd, cpath = tempfile.mkstemp(suffix='_transpiled.c', prefix=prefix + '_')
try:
with os.fdopen(cfd, 'w') as f:
f.write(transpiled)
if args.output:
compile(cpath, args.output)
else:
rc, out, err = run_c(cpath, prefix)
sys.stdout.write(out)
sys.stderr.write(err)
sys.exit(rc)
finally:
if os.path.exists(cpath):
os.remove(cpath)