Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

305 Zeilen
8.4KB

  1. #!/usr/bin/env python3
  2. import argparse
  3. import os
  4. from pathlib import Path
  5. import multiprocessing
  6. import itertools
  7. from concurrent.futures import ThreadPoolExecutor
  8. from typing import Sequence, Iterable, Dict, Tuple, List, NamedTuple
  9. import subprocess
  10. import time
  11. import re
  12. import sys
  13. ROOT = Path(__file__).parent.parent.absolute()
  14. INCLUDE_DIRS = [
  15. 'external/taywee-args/include',
  16. 'external/spdlog/include',
  17. 'external/wil/include',
  18. 'external/ranges-v3/include',
  19. ]
  20. class BuildOptions(NamedTuple):
  21. cxx: Path
  22. jobs: int
  23. static: bool
  24. debug: bool
  25. @property
  26. def is_msvc(self) -> bool:
  27. return is_msvc(self.cxx)
  28. @property
  29. def obj_suffix(self) -> str:
  30. return '.obj' if self.is_msvc else '.o'
  31. def is_msvc(cxx: Path) -> bool:
  32. return (not 'clang' in cxx.name) and 'cl' in cxx.name
  33. def have_ccache() -> bool:
  34. try:
  35. subprocess.check_output(['ccache', '--version'])
  36. return True
  37. except FileNotFoundError:
  38. return False
  39. def have_sccache() -> bool:
  40. try:
  41. subprocess.check_output(['sccache', '--version'])
  42. return True
  43. except FileNotFoundError:
  44. return False
  45. def _create_compile_command(opts: BuildOptions, cpp_file: Path,
  46. obj_file: Path) -> List[str]:
  47. if not opts.is_msvc:
  48. cmd = [
  49. str(opts.cxx),
  50. f'-I{ROOT / "src"}',
  51. '-std=c++17',
  52. '-Wall',
  53. '-Wextra',
  54. '-Werror',
  55. '-Wshadow',
  56. '-Wconversion',
  57. '-fdiagnostics-color',
  58. '-DFMT_HEADER_ONLY=1',
  59. '-pthread',
  60. '-c',
  61. str(cpp_file),
  62. f'-o{obj_file}',
  63. ]
  64. if have_ccache():
  65. cmd.insert(0, 'ccache')
  66. elif have_sccache():
  67. cmd.insert(0, 'sccache')
  68. if opts.static:
  69. cmd.append('-static')
  70. if opts.debug:
  71. cmd.extend(('-g', '-O0'))
  72. else:
  73. cmd.append('-O2')
  74. cmd.extend(
  75. itertools.chain.from_iterable(('-isystem', str(ROOT / subdir))
  76. for subdir in INCLUDE_DIRS))
  77. return cmd
  78. else:
  79. cmd = [
  80. str(opts.cxx),
  81. '/W4',
  82. '/WX',
  83. '/nologo',
  84. '/EHsc',
  85. '/std:c++latest',
  86. '/permissive-',
  87. '/experimental:preprocessor',
  88. '/wd5105', # winbase.h
  89. '/wd4459', # Shadowing
  90. '/DWIN32_LEAN_AND_MEAN',
  91. '/DNOMINMAX',
  92. '/DFMT_HEADER_ONLY=1',
  93. '/D_CRT_SECURE_NO_WARNINGS',
  94. '/diagnostics:caret',
  95. '/experimental:external',
  96. f'/I{ROOT / "src"}',
  97. str(cpp_file),
  98. '/c',
  99. f'/Fo{obj_file}',
  100. ]
  101. if have_ccache():
  102. cmd.insert(0, 'ccache')
  103. if opts.debug:
  104. cmd.extend(('/Od', '/DEBUG', '/Z7'))
  105. else:
  106. cmd.append('/O2')
  107. if opts.static:
  108. cmd.append('/MT')
  109. else:
  110. cmd.append('/MD')
  111. cmd.extend(f'/external:I{ROOT / subdir}' for subdir in INCLUDE_DIRS)
  112. return cmd
  113. def _compile_src(opts: BuildOptions, cpp_file: Path) -> Tuple[Path, Path]:
  114. build_dir = ROOT / '_build'
  115. src_dir = ROOT / 'src'
  116. relpath = cpp_file.relative_to(src_dir)
  117. obj_path = build_dir / relpath.with_name(relpath.name + opts.obj_suffix)
  118. obj_path.parent.mkdir(exist_ok=True, parents=True)
  119. cmd = _create_compile_command(opts, cpp_file, obj_path)
  120. msg = f'Compile C++ file: {cpp_file.relative_to(ROOT)}'
  121. print(msg)
  122. start = time.time()
  123. res = subprocess.run(
  124. cmd,
  125. stdout=subprocess.PIPE,
  126. stderr=subprocess.STDOUT,
  127. )
  128. if res.returncode != 0:
  129. raise RuntimeError(
  130. f'Compile command ({cmd}) failed for {cpp_file}:\n{res.stdout.decode()}'
  131. )
  132. stdout: str = res.stdout.decode()
  133. stdout = re.sub(r'^{cpp_file.name}\r?\n', stdout, '')
  134. fname_head = f'{cpp_file.name}\r\n'
  135. if stdout:
  136. print(stdout, end='')
  137. end = time.time()
  138. print(f'{msg} - Done: {end - start:.2}s')
  139. return cpp_file, obj_path
  140. def compile_sources(opts: BuildOptions,
  141. sources: Iterable[Path]) -> Dict[Path, Path]:
  142. pool = ThreadPoolExecutor(opts.jobs)
  143. return {
  144. src: obj
  145. for src, obj in pool.map(lambda s: _compile_src(opts, s), sources)
  146. }
  147. def _create_archive_command(opts: BuildOptions,
  148. objects: Iterable[Path]) -> Tuple[Path, List[str]]:
  149. if opts.is_msvc:
  150. lib_file = ROOT / '_build/libddslim.lib'
  151. cmd = ['lib', '/nologo', f'/OUT:{lib_file}', *map(str, objects)]
  152. return lib_file, cmd
  153. else:
  154. lib_file = ROOT / '_build/libddslim.a'
  155. cmd = ['ar', 'rsc', str(lib_file), *map(str, objects)]
  156. return lib_file, cmd
  157. def make_library(opts: BuildOptions, objects: Iterable[Path]) -> Path:
  158. lib_file, cmd = _create_archive_command(opts, objects)
  159. if lib_file.exists():
  160. lib_file.unlink()
  161. print(f'Creating static library {lib_file}')
  162. subprocess.check_call(cmd)
  163. return lib_file
  164. def _create_exe_link_command(opts: BuildOptions, obj: Path, lib: Path,
  165. out: Path) -> List[str]:
  166. if not opts.is_msvc:
  167. cmd = [
  168. str(opts.cxx),
  169. '-pthread',
  170. str(obj),
  171. str(lib),
  172. '-lstdc++fs',
  173. f'-o{out}',
  174. ]
  175. if opts.static:
  176. cmd.extend((
  177. '-static',
  178. # See: https://stackoverflow.com/questions/35116327/when-g-static-link-pthread-cause-segmentation-fault-why
  179. '-Wl,--whole-archive',
  180. '-lpthread',
  181. '-Wl,--no-whole-archive',
  182. ))
  183. return cmd
  184. else:
  185. cmd = [
  186. str(opts.cxx),
  187. '/nologo',
  188. '/W4',
  189. '/WX',
  190. '/Z7',
  191. '/DEBUG',
  192. 'rpcrt4.lib',
  193. f'/Fe{out}',
  194. str(lib),
  195. str(obj),
  196. ]
  197. if opts.debug:
  198. cmd.append('/DEBUG')
  199. if opts.static:
  200. cmd.append('/MT')
  201. else:
  202. cmd.append('/MD')
  203. return cmd
  204. def link_exe(opts: BuildOptions, obj: Path, lib: Path, *,
  205. out: Path = None) -> Path:
  206. if out is None:
  207. basename = obj.stem
  208. out = ROOT / '_build/test' / (basename + '.exe')
  209. out.parent.mkdir(exist_ok=True, parents=True)
  210. print(f'Linking executable {out}')
  211. cmd = _create_exe_link_command(opts, obj, lib, out)
  212. subprocess.check_call(cmd)
  213. return out
  214. def run_test(exe: Path) -> None:
  215. print(f'Running test: {exe}')
  216. subprocess.check_call([str(exe)])
  217. def main(argv: Sequence[str]) -> int:
  218. parser = argparse.ArgumentParser()
  219. parser.add_argument(
  220. '--test', action='store_true', help='Build and run tests')
  221. parser.add_argument(
  222. '--cxx', help='Path/name of the C++ compiler to use.', required=True)
  223. parser.add_argument(
  224. '--jobs',
  225. '-j',
  226. type=int,
  227. help='Set number of parallel build threads',
  228. default=multiprocessing.cpu_count() + 2)
  229. parser.add_argument(
  230. '--debug',
  231. action='store_true',
  232. help='Build with debug information and disable optimizations')
  233. parser.add_argument(
  234. '--static', action='store_true', help='Build a static executable')
  235. args = parser.parse_args(argv)
  236. all_sources = set(ROOT.glob('src/**/*.cpp'))
  237. test_sources = set(ROOT.glob('src/**/*.test.cpp'))
  238. main_sources = set(ROOT.glob('src/**/*.main.cpp'))
  239. lib_sources = (all_sources - test_sources) - main_sources
  240. build_opts = BuildOptions(
  241. cxx=Path(args.cxx),
  242. jobs=args.jobs,
  243. static=args.static,
  244. debug=args.debug)
  245. objects = compile_sources(build_opts, sorted(all_sources))
  246. lib = make_library(build_opts, (objects[p] for p in lib_sources))
  247. test_objs = (objects[p] for p in test_sources)
  248. pool = ThreadPoolExecutor(build_opts.jobs)
  249. test_exes = list(
  250. pool.map(lambda o: link_exe(build_opts, o, lib), test_objs))
  251. main_exe = link_exe(
  252. build_opts,
  253. objects[next(iter(main_sources))],
  254. lib,
  255. out=ROOT / '_build/ddslim')
  256. if args.test:
  257. list(pool.map(run_test, test_exes))
  258. print(f'Main executable generated at {main_exe}')
  259. return 0
  260. if __name__ == "__main__":
  261. sys.exit(main(sys.argv[1:]))