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.

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