Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

build.py 7.8KB

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