Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

267 linhas
7.3KB

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