Debian Codegraph @

cmake/scripts/gen_header.py

raw
1 #!/usr/bin/env python3
2
3 # This script will generate interfacing headers from the official headers of solvers.
4 # Note that since this is not an actual parser for the headers this is not a foolproof
5 # method. Please make sure that the generated file do not contain multiple definitions
6 # of the same identifier. This generally suggest a ifdef statement was read ignored.
7 #
8 # Generally this script goes over the header files given as "source_names" and looks
9 # for declarations of macros, enumerated types, and typedefinitions. It then compares
10 # each of these definitions to see if they are used in the files declared in "usage".
11 # Additional control is added by the "ignore" and "include" fields to correct
12 # the generated header file.
13
14 import os
15 import re
16 import sys
17 from itertools import chain
18 from pathlib import Path
19 from typing import List, Optional
20
21 STDCALL_PREPEND = """#if !defined(WIN32) && !defined(WIN64)
22 #define __cdecl
23 #define __stdcall
24 #endif
25 """
26
27
28 def find_file(file_name: str, search_path: List[Path]) -> Optional[Path]:
29 for p in search_path:
30 path = p / file_name
31 if path.exists():
32 return path
33 return None
34
35
36 def remove_comments(code: str):
37 code = re.sub(r"/\*(.|\n)*?\*/", "", code)
38 code = re.sub(r"//.*", "", code)
39 return code
40
41
42 # Generator for the definitions in the header of the given Path.
43 def definitions(path: Path):
44
45 with path.open() as file:
46 end = True
47 buffer = ""
48 for line in file.readlines():
49 buffer += line
50
51 if line.endswith("\\\n"):
52 buffer = buffer[:-2]
53 continue
54
55 # macro definitions
56 match = re.search(r"#define\s+(\w+).*[ \t]+\S+[^\n]*\n", buffer)
57 if match:
58 text = remove_comments(match[0])
59 yield (match[1], text)
60 buffer = ""
61 continue
62 buffer = ""
63
64 txt = path.read_text()
65 # macro definitions
66 for match in re.findall(r"^\s*(enum\s+(\w+)([^;]|\n)*;)", txt, flags=re.MULTILINE):
67 text = remove_comments(match[0]) + "\n"
68 yield (match[1], text)
69 # type definitions
70 for match in re.findall(r"(typedef\s+.+\s+\*?\s*(\w+)\s*;)", txt):
71 text = remove_comments(match[0]) + "\n"
72 yield (match[1], text)
73
74
75 if __name__ == "__main__":
76 if len(sys.argv) <= 1:
77 print(
78 "Header generator usage:\n\tgen_header.py <solver> [search_location...]",
79 file=sys.stderr,
80 )
81 exit(1)
82 solver = sys.argv[1].upper()
83 root = Path(os.path.realpath(__file__)).parent.parent.parent
84
85 # Set addition search paths provided from command line
86 search_path = []
87 for i in range(2, len(sys.argv)):
88 search_path.append(Path(sys.argv[i]).resolve())
89 search_path.append(Path(sys.argv[i]).resolve() / "include")
90
91 # Set all solver specific settings
92 output = root / "include/minizinc/_thirdparty"
93 prepend = ""
94 ignore = set() # identifiers to be ignore (e.g., platform dependent definitions)
95 include = (
96 set()
97 ) # identifiers that must be included (e.g., identifiers used by included macros)
98
99 if solver == "CPLEX":
100 output /= "cplex_interface.h"
101 source_names = ["ilcplex/cpxconst.h"]
102 prepend = """#ifdef _MSC_VER
103 typedef __int64 CPXLONG;
104 #else
105 typedef long long CPXLONG;
106 #endif
107 #ifdef _WIN32
108 #define CPXPUBLIC __stdcall
109 #else
110 #define CPXPUBLIC
111 #endif
112 """
113 ignore = {"CPXLONG", "CPXPUBLIC"}
114 usage = [
115 root / "solvers/MIP/MIP_cplex_solverfactory.cpp",
116 root / "solvers/MIP/MIP_cplex_wrap.cpp",
117 root / "include/minizinc/solvers/MIP/MIP_cplex_solverfactory.hh",
118 root / "include/minizinc/solvers/MIP/MIP_cplex_wrap.hh",
119 ]
120
121 for ver in [
122 "1210",
123 "129",
124 "128",
125 "1271",
126 "127",
127 "1263",
128 "1262",
129 "1261",
130 "126",
131 "201",
132 ]:
133 paths = [
134 f"/opt/ibm/ILOG/CPLEX_Studio{ver}",
135 f"/opt/IBM/ILOG/CPLEX_Studio{ver}",
136 f"C:\\Program Files\\IBM\\ILOG\\CPLEX_Studio{ver}",
137 f"C:\\Program Files (x86)\\IBM\\ILOG\\CPLEX_Studio{ver}",
138 f"~/Applications/IBM/ILOG/CPLEX_Studio{ver}",
139 f"/Applications/IBM/ILOG/CPLEX_Studio{ver}",
140 f"/Applications/CPLEX_Studio{ver}",
141 ]
142 search_path.extend([Path(p) / "include" for p in paths if Path(p).exists()])
143 search_path.extend(
144 [Path(p) / "cplex/include" for p in paths if Path(p).exists()]
145 )
146
147 elif solver == "GUROBI":
148 output /= "gurobi_interface.h"
149 source_names = ["gurobi_c.h"]
150 prepend = STDCALL_PREPEND
151 usage = [
152 root / "solvers/MIP/MIP_gurobi_solverfactory.cpp",
153 root / "solvers/MIP/MIP_gurobi_wrap.cpp",
154 root / "include/minizinc/solvers/MIP/MIP_gurobi_solverfactory.hh",
155 root / "include/minizinc/solvers/MIP/MIP_gurobi_wrap.hh",
156 ]
157 for ver in [
158 "913",
159 "912",
160 "911",
161 "910",
162 "903",
163 "902",
164 "901",
165 "900",
166 "811",
167 "810",
168 "801",
169 "752",
170 "702",
171 ]:
172 paths = [
173 f"/opt/gurobi{ver}/linux64",
174 f"C:\\gurobi{ver}\\win64",
175 f"C:\\gurobi{ver}\\win32",
176 f"/Library/gurobi{ver}/mac64",
177 f"/Library/gurobi{ver}/macos_universal2",
178 ]
179 search_path.extend([Path(p) / "include" for p in paths if Path(p).exists()])
180 elif solver == "SCIP":
181 output /= "scip_interface.h"
182 source_names = [
183 "scip/def.h",
184 "scip/type_scip.h",
185 "scip/type_retcode.h",
186 "scip/type_message.h",
187 "scip/type_prob.h",
188 "scip/type_var.h",
189 "scip/type_stat.h",
190 "scip/type_sol.h",
191 "scip/type_event.h",
192 "scip/type_cons.h",
193 "scip/type_paramset.h",
194 "scip/type_lp.h",
195 "scip/cons_orbitope.h",
196 "symmetry/type_symmetry.h"
197 ]
198 include = {
199 "SCIP_Retcode",
200 "SCIP_Vartype",
201 "SCIP_Status",
202 "SCIP_Objsense",
203 "SCIP_BoundType",
204 "SCIP_OrbitopeType",
205 }
206 prepend = """#if !defined(_MSC_VER) || _MSC_VER > 1600
207 #ifdef __cplusplus
208 #define __STDC_FORMAT_MACROS
209 #endif
210 #include <inttypes.h>
211 #else
212 #define PRIx64 "llx"
213 #endif
214 #ifdef SCIP_DEBUG
215 #define SCIPdebugMessage printf("[%s:%d] debug: ", __FILE__, __LINE__), printf
216 #else
217 #define SCIPdebugMessage while( FALSE ) printf
218 #endif
219 """
220 usage = [
221 root / "solvers/MIP/MIP_scip_solverfactory.cpp",
222 root / "solvers/MIP/MIP_scip_wrap.cpp",
223 root / "include/minizinc/solvers/MIP/MIP_scip_solverfactory.hh",
224 root / "include/minizinc/solvers/MIP/MIP_scip_wrap.hh",
225 ]
226 elif solver == "XPRESS":
227 output /= "xpress_interface.h"
228 source_names = ["xprb.h", "xprs.h"]
229 prepend = """#ifdef _WIN32
230 #define XPRS_CC __stdcall
231 #else
232 #define XPRS_CC
233 #endif
234 #if defined(_WIN32) || defined(_WIN64)
235 #define XB_CC __stdcall
236 #else
237 #define XB_CC
238 #endif
239 #ifdef _WIN32
240 #define XPRSint64 __int64
241 #elif defined(__LP64__) || defined(_LP64) || defined(__ILP64__) || defined(_ILP64)
242 #define XPRSint64 long
243 #else
244 #define XPRSint64 long long
245 #endif
246 """
247 ignore = {"XB_CC", "XPRS_CC", "XPRSint64"}
248 include = {
249 "XB_INFINITY",
250 "XB_PL",
251 "XB_BV",
252 "XB_UI",
253 "XB_L",
254 "XB_G",
255 "XB_E",
256 "XB_MAXIM",
257 "XB_MINIM",
258 "XB_LP",
259 "XB_MPS",
260 "XB_XO_SOL",
261 "XB_MIP_NOT_LOADED",
262 "XB_MIP_NO_SOL_FOUND",
263 "XB_MIP_INFEAS",
264 "XB_MIP_OPTIMAL",
265 "XB_MIP_UNBOUNDED",
266 }
267 usage = [
268 root / "solvers/MIP/MIP_xpress_solverfactory.cpp",
269 root / "solvers/MIP/MIP_xpress_wrap.cpp",
270 root / "include/minizinc/solvers/MIP/MIP_xpress_solverfactory.hh",
271 root / "include/minizinc/solvers/MIP/MIP_xpress_wrap.hh",
272 ]
273 search_path.extend(
274 [
275 "/opt/xpressmp/include",
276 "C:\\xpressmp\\Applications\\FICO Xpress\\xpressmp\\include",
277 ]
278 )
279 else:
280 print(
281 f"ERROR: solver `{sys.argv[1]}' unknown. Unable to generate headers",
282 file=sys.stderr,
283 )
284 exit(1)
285
286 # Find Source Files
287 source_files = []
288 for name in source_names:
289 f = find_file(name, search_path)
290 if f is None:
291 print(
292 f"ERROR: Unable to locate source file `{name}'. Did you forget to specify a search location?",
293 file=sys.stderr,
294 )
295 exit(1)
296 source_files.append(f)
297
298 # Filter definitions on usage and place in generated header file
299 combined_usage = "\n".join([f.read_text() for f in usage])
300 with output.open("w") as out:
301 out.write(prepend)
302 for (ident, define) in chain(*[definitions(f) for f in source_files]):
303 if ident in include or (ident not in ignore and ident in combined_usage):
304 out.write(define)