-
Notifications
You must be signed in to change notification settings - Fork 0
/
souffle-compile-msvc-static.py
246 lines (212 loc) · 9.42 KB
/
souffle-compile-msvc-static.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
#!/usr/bin/env python3
JSON_DATA_TEXT = """{
"compiler": "cl.exe",
"includes": "-I{{root}}/include -I{{root}}/third-party/include",
"std_flag": "-std:c++17",
"cxx_flags": "/DWIN32 /D_WINDOWS /GR /EHsc -openmp",
"cxx_link_flags": "",
"release_cxx_flags": "/O2 /Ob2 /DNDEBUG /MT",
"debug_cxx_flags": "/Zi /Ob0 /Od /RTC1 /MTd",
"definitions": "-DRAM_DOMAIN_SIZE=64 -DUSE_LIBZ -DUSE_SQLITE -DUSE_CUSTOM_GETOPTLONG",
"compile_options": " /bigobj /wd5105 /wd6326 /permissive- /Zc:preprocessor /EHsc",
"link_options": "/link /libpath:{{root}}/third-party/lib sqlite3.lib zlib.lib",
"rpaths": "",
"outname_fmt": "/Fe:{}",
"libdir_fmt": "/libpath:{}",
"libname_fmt": "{}.lib",
"rpath_fmt": "",
"path_delimiter": ";",
"exe_extension": ".exe",
"source_include_dir": "{{root}}/include",
"jni_includes": ";"
}"""
# --- JSON_DATA_TEXT variable is inserted before this line ---
## Example of JSON_DATA_TEXT
if not JSON_DATA_TEXT:
JSON_DATA_TEXT = """{
"compiler": "/usr/bin/c++",
"compiler_id": "GNU",
"compiler_version": "8.3.0",
"msvc_version": "",
"includes": "-I/usr/include",
"std_flag": "-std=c++17",
"cxx_flags": " -fopenmp",
"cxx_link_flags": "",
"release_cxx_flags": "-O3 ",
"debug_cxx_flags": "-g",
"definitions": "-DRAM_DOMAIN_SIZE=64 -DUSE_NCURSES -DUSE_LIBZ -DUSE_SQLITE",
"compile_options": "",
"link_options": "-pthread -ldl -lstdc++fs /usr/lib/x86_64-linux-gnu/libsqlite3.so /usr/lib/x86_64-linux-gnu/libz.so /usr/lib/x86_64-linux-gnu/libncurses.so",
"rpaths": "/usr/lib/x86_64-linux-gnu:/usr/lib/x86_64-linux-gnu",
"outname_fmt": "-o {}",
"libdir_fmt": "-L{}",
"libname_fmt": "-l{}",
"rpath_fmt": "-Wl,-rpath,{}",
"path_delimiter": ":",
"exe_extension": "",
"source_include_dir": "",
"jni_includes": ""
}"""
import argparse
import json
import os
import pathlib
import shutil
import subprocess
import sys
import tempfile
JSON_DATA_TEXT = JSON_DATA_TEXT.replace("{{root}}", str(pathlib.Path(__file__).parent.parent).replace("\\", "/"))
# run command and return status object
def launch_command(cmd, descr, verbose=False):
if verbose:
sys.stdout.write(cmd + "\n")
status = subprocess.run(cmd, capture_output=True, text=True, shell=True)
if status.returncode != 0:
sys.stdout.write(status.stdout)
sys.stderr.write(status.stderr)
raise RuntimeError("Error: {}. Command: {}".format(descr, cmd))
return status
# run command and return the standard output as a string
def capture_command_output(cmd, descr, verbose=False):
status = launch_command(cmd, descr, verbose)
return status.stdout
conf = json.loads(JSON_DATA_TEXT)
OUTNAME_FMT = conf['outname_fmt']
LIBDIR_FMT = conf['libdir_fmt']
LIBNAME_FMT = conf['libname_fmt']
RPATH_FMT = conf['rpath_fmt']
PATH_DELIMITER = conf['path_delimiter']
RPATHS = conf['rpaths'].split(PATH_DELIMITER)
exeext = conf['exe_extension']
SOURCE_INCLUDE_DIR = conf['source_include_dir']
JNI_INCLUDES = conf['jni_includes'].split(PATH_DELIMITER)
workdir = os.getcwd()
scriptdir = pathlib.Path(os.path.dirname(os.path.abspath(__file__)))
parser = argparse.ArgumentParser(description="Compile a C++ source file generated by Souffle")
parser.add_argument('-l', action='append', default=[], metavar='LIBNAME', dest='lib_names', type=str, help="Basename of a functors library. eg: `-l functors` => libfunctors.dll")
parser.add_argument('-L', action='append', default=[], metavar='LIBDIR', dest='lib_dirs', type=lambda p: pathlib.Path(p).absolute(), help="Search directory for functors libraries")
parser.add_argument('-g', action='store_true', dest='debug', help="Debug build type")
parser.add_argument('-s', metavar='LANG', dest='swiglang', choices=["java", "python"], help="use SWIG interface to generate into LANG language")
parser.add_argument('-v', action='store_true', dest='verbose', help="Verbose output")
parser.add_argument('source', nargs='+', metavar='SOURCE', type=lambda p: pathlib.Path(p).absolute(), help="C++ source files")
parser.add_argument('-o', metavar='BINARY', dest='output', type=lambda p: pathlib.Path(p).absolute(), help="Binary file name")
args = parser.parse_args()
if not args.output:
raise RuntimeError("Missing output file name in souffle-compile")
for f in args.source:
if not os.path.isfile(f):
raise RuntimeError("Cannot open source file: '{}'".format(f))
# Check if the input file has a valid extension
for f in args.source:
extname = f.suffix
if extname != ".cpp":
raise RuntimeError("Source file is not a .cpp file: '{}'".format(f))
# Search for Souffle includes directory
souffle_include_dir = None
if (scriptdir / "include" / "souffle").exists():
souffle_include_dir = scriptdir / "include" / "souffle"
elif (scriptdir / ".." / "include" / "souffle").exists():
souffle_include_dir = scriptdir / ".." / "include" / "souffle"
elif SOURCE_INCLUDE_DIR and (pathlib.Path(SOURCE_INCLUDE_DIR) / "souffle").exists():
souffle_include_dir = (pathlib.Path(SOURCE_INCLUDE_DIR) / "souffle")
if args.swiglang:
if not (souffle_include_dir and (souffle_include_dir / "swig").exists()):
raise RuntimeError("Cannot find 'souffle/swig' include directory")
swig_include_dir = (souffle_include_dir / "swig")
with tempfile.TemporaryDirectory() as tmpdir:
shutil.copy(swig_include_dir / "SwigInterface.h", tmpdir)
shutil.copy(swig_include_dir / "SwigInterface.i", tmpdir)
os.chdir(tmpdir)
launch_command("swig -c++ -\"{}\" SwigInterface.i".format(args.swiglang), "SWIG generation", verbose=args.verbose)
if args.swiglang == "python":
swig_flags = capture_command_output("python3-config --cflags", "Python config", verbose=args.verbose)
swig_ldflags = capture_command_output("python3-config --ldflags", "Python config", verbose=args.verbose)
swig_outname = "_SwigInterface.so"
elif args.swiglang == "java":
swig_flags = " ".join(["-I{}".format(dir) for dir in JNI_INCLUDES])
swig_ldflags = ""
swig_outname = "libSwigInterface.so"
# compile swig interface and program
cmd = []
cmd.append('"{}"'.format(conf['compiler']))
cmd.append("-fPIC")
cmd.append("-c")
cmd.append("-D__EMBEDDED_SOUFFLE__")
cmd.append("SwigInterface_wrap.cxx")
for f in args.source:
cmd.append(str(f))
cmd.append(conf['definitions'])
cmd.append(conf['compile_options'])
cmd.append(conf['includes'])
cmd.append(conf['std_flag'])
cmd.append(conf['cxx_flags'])
if args.debug:
cmd.append(conf['debug_cxx_flags'])
else:
cmd.append(conf['release_cxx_flags'])
cmd.append(swig_flags)
cmd = " ".join(cmd)
launch_command(cmd, "Compilation of SWIG C++", verbose=args.verbose)
# link swig interface and program
cmd = []
cmd.append('"{}"'.format(conf['compiler']))
cmd.append("-shared")
cmd.append("SwigInterface_wrap.o")
cmd.append(os.path.basename(args.output) + ".o")
cmd.append("-o")
cmd.append(swig_outname)
cmd.append(conf['definitions'])
cmd.append(conf['compile_options'])
cmd.append(conf['includes'])
cmd.append(conf['std_flag'])
cmd.append(conf['cxx_flags'])
if args.debug:
cmd.append(conf['debug_cxx_flags'])
else:
cmd.append(conf['release_cxx_flags'])
cmd.append(conf['link_options'])
cmd.extend(list(map(lambda rpath: RPATH_FMT.format(rpath), RPATHS)))
cmd.extend(list(map(lambda libdir: LIBDIR_FMT.format(libdir), args.lib_dirs)))
cmd.extend(list(map(lambda libname: LIBNAME_FMT.format(libname), args.lib_names)))
cmd.append(swig_ldflags)
cmd = " ".join(cmd)
launch_command(cmd, "Link of SWIG C++", verbose=args.verbose)
if args.swiglang == "python":
shutil.copy("_SwigInterface.so", workdir)
shutil.copy("SwigInterface.py", workdir)
elif args.swiglang == "java":
shutil.copy("libSwigInterface.so", workdir)
for javasrc in pathlib.Path(tmpdir).glob("*.java"):
shutil.copy(javasrc, workdir)
# move generated files to same directory as cpp file
os.sys.exit(0)
else:
exepath = pathlib.Path("{}{}".format(args.output, exeext))
cmd = []
cmd.append('"{}"'.format(conf['compiler']))
cmd.append(conf['definitions'])
cmd.append(conf['compile_options'])
cmd.append(conf['includes'])
cmd.append(conf['std_flag'])
cmd.append(conf['cxx_flags'])
if args.debug:
cmd.append(conf['debug_cxx_flags'])
else:
cmd.append(conf['release_cxx_flags'])
cmd.append(OUTNAME_FMT.format(exepath))
for f in args.source:
cmd.append(str(f))
cmd.append(conf['link_options'])
cmd.extend(list(map(lambda rpath: RPATH_FMT.format(rpath), RPATHS)))
cmd.extend(list(map(lambda libdir: LIBDIR_FMT.format(libdir), args.lib_dirs)))
cmd.extend(list(map(lambda libname: LIBNAME_FMT.format(libname), args.lib_names)))
cmd = " ".join(cmd)
if args.verbose:
sys.stderr.write(cmd + "\n")
if exepath.exists():
exepath.unlink()
status = subprocess.run(cmd, capture_output=True, text=True, shell=True)
if status.returncode != 0:
sys.stdout.write(status.stdout)
sys.stderr.write(status.stderr)
os.sys.exit(status.returncode)