Debian Codegraph @

tests/cl.py

raw
1 #!/usr/bin/env python3
2
3 """
4 MSVC compiler wrapper
5
6 Configuring MSVC’s command line binary, `cl`, to run standalone is complicated and
7 involves interaction with fragile programming environments like PowerShell and/or Batch
8 files. To avoid relying on this, this script outsources compiler discovery and
9 configuration to CMake. This allows standalone compilation using any version of MSVC
10 CMake is able to successfully discover and use.
11
12 Though this script is intended as an MSVC wrapper, it is agnostic to the C compiler
13 being called. It can be used in combination with any C compiler that understands MSVC
14 options.
15 """
16
17 import io
18 import os
19 import re
20 import shlex
21 import subprocess
22 import sys
23 import tempfile
24 import textwrap
25 from pathlib import Path
26 from typing import Optional, Union
27
28
29 def run(args: list[Union[Path, str]]):
30 """run an external command, echoing it first"""
31 print(f"+ {shlex.join(str(x) for x in args)}", flush=True)
32 subprocess.run(args, check=True)
33
34
35 def safe_path(path: Union[Path, str]) -> str:
36 """
37 escape a path for use in a CMake file
38
39 Windows paths typically contain backslashes. E.g. C:\foo\bar. When inserted as-is
40 into CMakeLists.txt files, these are interpreted by CMake as escape sequences. To
41 properly propagate such paths through to CMake, they need to be either (1)
42 double-backslash escaped or (2) replaced with forward slashes.
43
44 Args:
45 path: An unescaped path.
46
47 Returns:
48 An equivalent, safe to write into a CMakeLists.txt.
49 """
50 return str(path).replace("\\", "/")
51
52
53 def make_cmakelists(args: list[str]) -> str:
54 """
55 reverse `cl` command line options into equivalent CMakeLists.txt content
56
57 Only a subset of `cl` options are recognized by this function. It can be extended to
58 recognize further options if/when they are necessary.
59
60 Args:
61 args: Command line options as would be given to the `cl` binary. `args[0]` is
62 expected to be `"cl"`.
63
64 Returns:
65 Content suitable for writing into a CMakeLists.txt. Any paths referenced will be
66 absolute, so this content can be written to an arbitrary directory.
67 """
68
69 # MSVC runtime library to link
70 crt: Optional[str] = None
71
72 # C sources to compile
73 sources: list[Path] = []
74
75 # binary output name
76 destination: Path = Path("main").absolute()
77
78 # ISO C standard to use, C{std}
79 std: Optional[int] = None
80
81 # macro definitions
82 definitions: list[str] = []
83
84 # extra C compiler flags
85 cflags: list[str] = []
86
87 # directories to put in the include path
88 includes: list[Path] = []
89
90 # libraries to link
91 libs: list[str] = []
92
93 i = 1
94 while i < len(args):
95
96 if m := re.match(r"[\-/]D(?P<definition>.*)$", args[i]):
97 definitions += [m.group("definition")]
98 i += 1
99 continue
100
101 if re.match(r"[\-/]Fe:$", args[i]):
102 if i + 1 == len(args):
103 raise RuntimeError("/Fe: option missing parameter")
104 destination = Path(args[i + 1]).absolute()
105 i += 2
106 continue
107
108 if re.match(r"[\-/]fsanitize\b", args[i]):
109 # pass these through as-is
110 cflags += [args[i]]
111 i += 1
112 continue
113
114 if re.match(r"[\-/]I$", args[i]):
115 if i + 1 == len(args):
116 raise RuntimeError("/I option missing parameter")
117 includes += [Path(args[i + 1]).resolve()]
118 i += 2
119 continue
120
121 if m := re.match(r"[\-/]I(?P<include>.+)$", args[i]):
122 includes += [Path(m.group("include")).resolve()]
123 i += 1
124 continue
125
126 if re.match(r"[\-/]link$", args[i]):
127 # swallow everything else as libraries to link
128 libs += args[i + 1 :]
129 break
130
131 if re.match(r"[\-/]nologo$", args[i]):
132 # CMake will set this automatically
133 i += 1
134 continue
135
136 if re.match(r"[\-/]MD$", args[i]):
137 crt = "MultiThreadedDLL"
138 i += 1
139 continue
140
141 if re.match(r"[\-/]MDd$", args[i]):
142 crt = "MultiThreadedDebugDLL"
143 i += 1
144 continue
145
146 if m := re.match(r"[\-/]std:c(?P<std>\d+)$", args[i]):
147 std = int(m.group("std"))
148 i += 1
149 continue
150
151 if re.match(r"[\-/]Wall$", args[i]):
152 cflags += [args[i]]
153 i += 1
154 continue
155
156 # pass through targeted warning enable/disable
157 if re.match(r"[\-/]w[de]\d+$", args[i]):
158 cflags += [args[i]]
159 i += 1
160 continue
161
162 if re.match(r"\w", args[i]):
163 sources += [Path(args[i]).absolute()]
164 i += 1
165 continue
166
167 raise RuntimeError(f"unrecognized cl option {args[i]}")
168
169 res = io.StringIO()
170
171 res.write(
172 textwrap.dedent(
173 """\
174 cmake_minimum_required(VERSION 3.21 FATAL_ERROR)
175 project(temp C)
176 """
177 )
178 )
179
180 if std is not None:
181 res.write(
182 textwrap.dedent(
183 f"""\
184 set(CMAKE_C_STANDARD {std})
185 set(CMAKE_C_STANDARD_REQUIRED ON)
186 """
187 )
188 )
189 if std >= 11:
190 res.write(
191 textwrap.dedent(
192 """\
193 if(${CMAKE_C_COMPILER_ID} STREQUAL MSVC)
194 set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /experimental:c11atomics")
195 endif()
196 """
197 )
198 )
199
200 res.write("add_executable(main\n")
201 for s in sources:
202 res.write(f" {safe_path(s)}\n")
203 res.write(")\n")
204
205 for d in definitions:
206 res.write(f"target_compile_definitions(main PRIVATE {d})\n")
207
208 if len(cflags) > 0:
209 res.write("include(CheckCCompilerFlag)\n")
210 for index, f in enumerate(cflags):
211 res.write(
212 textwrap.dedent(
213 f"""\
214 check_c_compiler_flag({f} WAS_SUPPORTED{index})
215 if(NOT WAS_SUPPORTED{index})
216 message(FATAL_ERROR "compiler does not understand {f}")
217 endif()
218 target_compile_options(main PRIVATE {f})
219 """
220 )
221 )
222
223 for i in includes:
224 res.write(f"target_include_directories(main PRIVATE {safe_path(i)})\n")
225
226 if crt is not None:
227 res.write(
228 f"set_target_properties(main PROPERTIES MSVC_RUNTIME_LIBRARY {crt})\n"
229 )
230
231 for index, l in enumerate(libs):
232 if m := re.match(r"(?P<libname>\w+)\.lib$", l):
233 res.write(
234 textwrap.dedent(
235 f"""\
236 find_library(LIB{index} {m.group('libname')} REQUIRED)
237 target_link_libraries(main PRIVATE ${{LIB{index}}})
238 """
239 )
240 )
241 else:
242 lib = Path(l).resolve()
243 res.write(
244 textwrap.dedent(
245 f"""\
246 find_library(
247 LIB{index} {lib.name}
248 PATHS {safe_path(lib.parent)}
249 REQUIRED
250 NO_DEFAULT_PATH
251 )
252 target_link_libraries(main PRIVATE ${{LIB{index}}})
253 """
254 )
255 )
256
257 res.write(
258 textwrap.dedent(
259 f"""\
260 install(PROGRAMS
261 $<TARGET_FILE:main>
262 DESTINATION {safe_path(destination.parent)}
263 RENAME {destination.name}
264 )
265 """
266 )
267 )
268
269 return res.getvalue()
270
271
272 def main(args: list[str]) -> int:
273 """entry point"""
274
275 # construct CMakeLists.txt content equivalent to our options
276 cmakelists = make_cmakelists(args)
277
278 # dump this for easier debugging
279 print(f'{"-" * 37} CMakeLists.txt {"-" * 37}', flush=True)
280 print(f'{cmakelists}{"-" * 80}', flush=True)
281
282 with tempfile.TemporaryDirectory() as t:
283 tmp = Path(t)
284
285 # setup a hierarchy for a CMake build
286 source = tmp / "src"
287 source.mkdir(parents=True)
288 build = tmp / "build"
289 (source / "CMakeLists.txt").write_text(cmakelists, encoding="utf-8")
290
291 # determine x86 vs x64
292 if platform := os.environ.get("project_platform"):
293 arch = ["-A", platform]
294 else:
295 arch = []
296
297 # configure and run the build
298 paranoia = ["--log-level=VERBOSE", "--warn-uninitialized", "-Werror-dev"]
299 run(["cmake"] + arch + ["-S", source, "-B", build] + paranoia)
300 run(["cmake", "--build", build, "--verbose"])
301 run(["cmake", "--build", build, "--target", "install", "--verbose"])
302
303 return 0
304
305
306 if __name__ == "__main__":
307 sys.exit(main(sys.argv))