split-tests.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  1. #!/usr/bin/env python3
  2. """Splits tests/tests.cpp (with every #include "*.inc" it pulls in) into N translation units at build time.
  3. tests/tests.cpp stays the single source of truth and keeps compiling on its own (the fallback). Each generated chunk is
  4. the whole test text with the .inc files inlined (#line keeps __FILE__ / __LINE__ as in the single-TU build), but only
  5. the bodies of the TESTs it owns: every other TEST body is emptied (its newlines kept). So helpers stay visible to every
  6. chunk while the heavy part (the ~1400 test bodies) is compiled once, spread over N parallel compilers.
  7. What is shared between the chunks (it lives in lynx_split_main.cpp, compiled once):
  8. - the check / failure counters, the FL data folder (realFlpDir) and the test registry;
  9. - the registry is sorted by the TEST's position in the text, so tests run in exactly the single-TU order.
  10. main() is kept in chunk 0 only; namespace-scope definitions outside anonymous namespaces get `inline` (one copy).
  11. usage: split-tests.py <tests.cpp> <out dir> <N> exit status != 0: use the single-TU build
  12. """
  13. import os
  14. import re
  15. import sys
  16. def fail(msg):
  17. sys.stderr.write("split-tests: " + msg + "\n")
  18. sys.exit(1)
  19. INC = re.compile(r'^\s*#\s*include\s+"([^"]+\.inc)"\s*(//.*)?$')
  20. QUOTE = re.compile(r'^(\s*#\s*include\s+)"([^"]+)"(.*)$')
  21. ANY_INC = re.compile(r'^\s*#\s*include\s*[<"][^>"]+\.inc[>"]', re.M)
  22. def expand(path, display, seen, out_dir):
  23. """The text of `path` with its .inc includes inlined; #line directives keep __FILE__/__LINE__ unchanged."""
  24. if path in seen:
  25. fail("recursive include of " + path)
  26. seen = seen | {path}
  27. out = ['#line 1 "%s"\n' % display]
  28. with open(path, encoding="utf-8") as f:
  29. lines = f.readlines()
  30. if lines and not lines[-1].endswith("\n"):
  31. lines[-1] += "\n"
  32. for i, line in enumerate(lines, 1):
  33. m = INC.match(line)
  34. if m:
  35. inc = os.path.join(os.path.dirname(path), m.group(1))
  36. if not os.path.isfile(inc):
  37. fail("missing " + inc)
  38. out.append(expand(inc, os.path.join(os.path.dirname(display), m.group(1)), seen, out_dir))
  39. out.append('#line %d "%s"\n' % (i + 1, display))
  40. else:
  41. q = QUOTE.match(line)
  42. if q and os.path.isfile(os.path.join(os.path.dirname(path), q.group(2))):
  43. # a header next to the tests (tests/DvsSignal.h): the chunks live elsewhere, point at it from there
  44. rel = os.path.relpath(os.path.join(os.path.dirname(path), q.group(2)), out_dir)
  45. line = '%s"%s"%s\n' % (q.group(1), rel, q.group(3))
  46. out.append(line)
  47. return "".join(out)
  48. def scan(text):
  49. """Lexes the C++ text: TEST bodies (start, end, name, head span) and namespace-scope definitions that need `inline`.
  50. Skips comments, string / char / raw string literals and preprocessor lines. Tracks the scope stack: 'A' anonymous
  51. namespace, 'N' named namespace, 'O' anything else (class, function, initializer...)."""
  52. n = len(text)
  53. i = 0
  54. stack = []
  55. tests = []
  56. pending_kind = None # what the next '{' opens: 'A', 'N' or None
  57. stmt_start = None # start of the current namespace-scope statement (outside anonymous namespaces)
  58. stmt_tokens = []
  59. inline_at = [] # offsets where `inline ` must be inserted
  60. only_first = [] # [start, end) of definitions kept in chunk 0 only (blanked elsewhere, newlines kept)
  61. alloc_depth = None
  62. test_head = None # (name, head start, head end) waiting for its body
  63. line_start = True
  64. ident = re.compile(r"[A-Za-z_][A-Za-z_0-9]*")
  65. while i < n:
  66. c = text[i]
  67. if c == "\n":
  68. line_start = True
  69. i += 1
  70. continue
  71. if c in " \t\r\f\v":
  72. i += 1
  73. continue
  74. if line_start and c == "#":
  75. # preprocessor line (with continuations)
  76. while i < n:
  77. j = text.find("\n", i)
  78. if j < 0:
  79. i = n
  80. break
  81. if text[j - 1] == "\\" or (text[j - 1] == "\r" and text[j - 2] == "\\"):
  82. i = j + 1
  83. continue
  84. i = j
  85. break
  86. continue
  87. line_start = False
  88. if text.startswith("//", i):
  89. j = text.find("\n", i)
  90. i = n if j < 0 else j
  91. continue
  92. if text.startswith("/*", i):
  93. j = text.find("*/", i + 2)
  94. if j < 0:
  95. fail("unterminated comment")
  96. i = j + 2
  97. continue
  98. m = re.compile(r'(?:u8|u|U|L)?R"([^ ()\\\t\n]{0,16})\(').match(text, i)
  99. if m and (i == 0 or not (text[i - 1].isalnum() or text[i - 1] == "_")):
  100. end = text.find(")" + m.group(1) + '"', m.end())
  101. if end < 0:
  102. fail("unterminated raw string")
  103. i = end + len(m.group(1)) + 2
  104. stmt_tokens.append("lit")
  105. continue
  106. if c == '"' or c == "'":
  107. j = i + 1
  108. while j < n and text[j] != c:
  109. if text[j] == "\\":
  110. j += 1
  111. elif text[j] == "\n":
  112. fail("newline in a literal at offset %d" % i)
  113. j += 1
  114. i = j + 1
  115. stmt_tokens.append("lit")
  116. continue
  117. if c.isdigit() or (c == "." and i + 1 < n and text[i + 1].isdigit()):
  118. # pp-number (digit separators ' included)
  119. j = i + 1
  120. while j < n and (text[j].isalnum() or text[j] in "._" or (text[j] == "'" and j + 1 < n and text[j + 1].isalnum())
  121. or (text[j] in "+-" and text[j - 1] in "eEpP")):
  122. j += 1
  123. i = j
  124. stmt_tokens.append("num")
  125. continue
  126. m = ident.match(text, i)
  127. if m:
  128. word = m.group(0)
  129. at_ns_scope = all(s != "O" for s in stack)
  130. if at_ns_scope and not stmt_tokens:
  131. stmt_start = i
  132. if at_ns_scope and word == "TEST" and not stmt_tokens:
  133. m2 = re.compile(r"TEST\s*\(\s*([A-Za-z_][A-Za-z_0-9]*)\s*\)").match(text, i)
  134. if not m2:
  135. fail("unexpected TEST at offset %d" % i)
  136. test_head = (m2.group(1), i, m2.end())
  137. i = m2.end()
  138. stmt_tokens.append("TEST")
  139. continue
  140. if word == "namespace" and at_ns_scope and not stmt_tokens:
  141. k = i + len(word)
  142. rest = re.compile(r"\s*([A-Za-z_][A-Za-z_0-9:]*)?\s*\{").match(text, k)
  143. if rest:
  144. pending_kind = "N" if rest.group(1) else "A"
  145. stmt_tokens.append(word)
  146. i = m.end()
  147. continue
  148. # punctuation
  149. if c == "{":
  150. if test_head is not None:
  151. tests.append({"name": test_head[0], "head": (test_head[1], test_head[2]), "open": i})
  152. test_head = None
  153. stack.append("T")
  154. i += 1
  155. continue
  156. if pending_kind:
  157. stack.append(pending_kind)
  158. pending_kind = None
  159. stmt_tokens = []
  160. i += 1
  161. continue
  162. if all(s != "O" and s != "T" for s in stack) and stmt_tokens:
  163. if "operator" in stmt_tokens and ("new" in stmt_tokens or "delete" in stmt_tokens) and "A" not in stack:
  164. # a replacement operator new / delete: one definition in the program (chunk 0), never inline
  165. only_first.append([stmt_start, None])
  166. alloc_depth = len(stack)
  167. else:
  168. note_definition(stack, stmt_tokens, stmt_start, inline_at, "{")
  169. stack.append("O")
  170. i += 1
  171. continue
  172. if c == "}":
  173. if not stack:
  174. fail("unbalanced } at offset %d" % i)
  175. kind = stack.pop()
  176. if alloc_depth is not None and len(stack) == alloc_depth:
  177. only_first[-1][1] = i + 1
  178. alloc_depth = None
  179. if kind == "T":
  180. tests[-1]["close"] = i
  181. stmt_tokens = []
  182. elif kind in "AN":
  183. stmt_tokens = []
  184. elif all(s != "O" and s != "T" for s in stack):
  185. # end of a class / function / initializer body at namespace scope
  186. if stmt_tokens and stmt_tokens[0] not in ("struct", "class", "union", "enum") and not top_level_eq(stmt_tokens):
  187. stmt_tokens = [] # a function definition ends without ';' (an '=' inside its parameters is a default)
  188. i += 1
  189. continue
  190. if c == ";":
  191. if all(s != "O" and s != "T" for s in stack):
  192. if stmt_tokens:
  193. note_definition(stack, stmt_tokens, stmt_start, inline_at, ";")
  194. stmt_tokens = []
  195. i += 1
  196. continue
  197. if all(s != "O" and s != "T" for s in stack):
  198. if not stmt_tokens and c not in "()[]<>,":
  199. stmt_start = i
  200. stmt_tokens.append(c)
  201. i += 1
  202. if stack:
  203. fail("unbalanced braces at the end (%s)" % "".join(stack))
  204. for t in tests:
  205. if "close" not in t:
  206. fail("TEST %s without a body" % t["name"])
  207. return tests, inline_at, only_first
  208. def top_level_eq(tokens):
  209. """An '=' outside parentheses: a variable with an initializer (it ends with ';'), not a function definition."""
  210. depth = 0
  211. for t in tokens:
  212. if t == "(":
  213. depth += 1
  214. elif t == ")":
  215. depth -= 1
  216. elif t == "=" and depth == 0:
  217. return True
  218. return False
  219. NON_DEFS = {"struct", "class", "union", "enum", "using", "typedef", "template", "static", "inline", "extern",
  220. "constexpr", "consteval", "constinit", "static_assert", "namespace", "friend", "TEST", "thread_local",
  221. "LYNX_SPLIT_MAIN"}
  222. def note_definition(stack, tokens, start, inline_at, end):
  223. """A namespace-scope declaration outside an anonymous namespace that defines a function or a variable gets `inline`
  224. (the same definition is compiled in every chunk)."""
  225. if "A" in stack or start is None:
  226. return
  227. first = tokens[0]
  228. if first in NON_DEFS or not (first[0].isalpha() or first[0] == "_" or first == ":"):
  229. return
  230. if end == ";" and ("(" in tokens and "=" not in tokens and tokens.index("(") < len(tokens)):
  231. # a function declaration (or a variable with a constructor call: rare in tests, also fine with inline)
  232. if "=" not in tokens and ")" in tokens and tokens[-1] == ")":
  233. return
  234. inline_at.append(start)
  235. def main():
  236. if len(sys.argv) != 4:
  237. fail("usage: split-tests.py <tests.cpp> <out dir> <N>")
  238. src, out, n = sys.argv[1], sys.argv[2], int(sys.argv[3])
  239. if n < 2:
  240. fail("N must be >= 2")
  241. text = expand(src, src, frozenset(), out)
  242. # the state shared by the chunks: exact lines of tests/tests.cpp (if one changes, the split is refused -> single TU)
  243. replace = [
  244. ("int failures = 0;", "int& failures = lynxSplitFailures;"),
  245. ("int checks = 0;", "int& checks = lynxSplitChecks;"),
  246. (" static std::vector<std::pair<const char*, std::function<void()>>> r;", " auto& r = lynxSplitRegistry();"),
  247. ("std::string realFlpDir;", "std::string& realFlpDir = lynxSplitFlpDir;"),
  248. ("int main (int argc, char** argv)", "LYNX_SPLIT_MAIN (int argc, char** argv)"),
  249. ]
  250. lines = text.split("\n")
  251. for old, new in replace:
  252. hits = [k for k, l in enumerate(lines) if l == old]
  253. if len(hits) != 1:
  254. fail("expected exactly one line %r in %s, found %d" % (old, src, len(hits)))
  255. lines[hits[0]] = new
  256. text = "\n".join(lines)
  257. if ANY_INC.search(text):
  258. fail("an .inc include was not inlined: " + ANY_INC.search(text).group(0))
  259. tests, inline_at, only_first = scan(text)
  260. if len(tests) < 2:
  261. fail("no TESTs found")
  262. names = [t["name"] for t in tests]
  263. if len(set(names)) != len(names):
  264. fail("duplicate TEST names")
  265. # balance the chunks by body size (greedy, biggest first); the order inside the registry is the text order
  266. owner = [0] * len(tests)
  267. load = [0] * n
  268. for k in sorted(range(len(tests)), key=lambda k: tests[k]["open"] - tests[k]["close"]):
  269. c = min(range(n), key=lambda c: load[c])
  270. owner[k] = c
  271. load[c] += tests[k]["close"] - tests[k]["open"]
  272. os.makedirs(out, exist_ok=True)
  273. def write(path, content):
  274. # only rewrite a file whose content changed (keeps the compiler caches warm)
  275. try:
  276. with open(path, encoding="utf-8") as f:
  277. if f.read() == content:
  278. return
  279. except OSError:
  280. pass
  281. with open(path + ".tmp", "w", encoding="utf-8") as f:
  282. f.write(content)
  283. os.replace(path + ".tmp", path)
  284. edits_inline = sorted(set(inline_at))
  285. for c in range(n):
  286. parts = []
  287. pos = 0
  288. events = [(t["head"][0], "head", k) for k, t in enumerate(tests)] + \
  289. [(t["open"] + 1, "body", k) for k, t in enumerate(tests) if owner[k] != c] + \
  290. [(p, "inline", -1) for p in edits_inline] + \
  291. ([(a, "blank", e) for a, e in only_first] if c != 0 else [])
  292. for at, kind, k in sorted(events):
  293. parts.append(text[pos:at])
  294. if kind == "blank":
  295. parts.append("\n" * text[at:k].count("\n"))
  296. pos = k
  297. elif kind == "inline":
  298. parts.append("inline ")
  299. pos = at
  300. elif kind == "head":
  301. t = tests[k]
  302. head = ("LYNX_TEST_OWN (%s, %d)" % (t["name"], k)) if owner[k] == c else ("LYNX_TEST_SKIP (%s)" % t["name"])
  303. parts.append(head)
  304. pos = t["head"][1]
  305. else:
  306. body = text[at:tests[k]["close"]]
  307. parts.append("\n" * body.count("\n"))
  308. pos = tests[k]["close"]
  309. parts.append(text[pos:])
  310. prelude = ("// generated by scripts/split-tests.py from %s: do not edit\n"
  311. "#define LYNX_SPLIT_CHUNK %d\n#include \"lynx_split.h\"\n" % (src, c))
  312. # helpers used only by the tests of other chunks are unused here: those warnings are the split's, not the code's
  313. prelude += ("#pragma GCC diagnostic ignored \"-Wunused-function\"\n"
  314. "#pragma GCC diagnostic ignored \"-Wunused-variable\"\n"
  315. "#pragma GCC diagnostic ignored \"-Wunused-const-variable\"\n"
  316. "#ifdef __clang__\n#pragma clang diagnostic ignored \"-Wunneeded-internal-declaration\"\n"
  317. "#pragma clang diagnostic ignored \"-Wunused-template\"\n"
  318. "#pragma clang diagnostic ignored \"-Wunused-member-function\"\n#endif\n")
  319. write(os.path.join(out, "chunk%02d.cpp" % c), prelude + "".join(parts))
  320. write(os.path.join(out, "lynx_split.h"), r'''// generated by scripts/split-tests.py: do not edit
  321. #pragma once
  322. #include <algorithm>
  323. #include <functional>
  324. #include <string>
  325. #include <utility>
  326. #include <vector>
  327. extern int lynxSplitFailures;
  328. extern int lynxSplitChecks;
  329. extern std::string lynxSplitFlpDir;
  330. std::vector<std::pair<const char*, std::function<void()>>>& lynxSplitRegistry();
  331. void lynxSplitAdd (int index, const char* name, void (*fn)());
  332. struct LynxSplitReg
  333. {
  334. LynxSplitReg (int index, const char* name, void (*fn)()) { lynxSplitAdd (index, name, fn); }
  335. };
  336. #define LYNX_TEST_OWN(name, index) \
  337. static void name(); \
  338. static LynxSplitReg reg_##name (index, #name, name); \
  339. static void name()
  340. #define LYNX_TEST_SKIP(name) [[maybe_unused]] static void name()
  341. #if LYNX_SPLIT_CHUNK == 0
  342. #define LYNX_SPLIT_MAIN int main
  343. #else
  344. #define LYNX_SPLIT_MAIN [[maybe_unused]] static int lynxSplitUnusedMain
  345. #endif
  346. ''')
  347. write(os.path.join(out, "lynx_split_main.cpp"), r'''// generated by scripts/split-tests.py: do not edit
  348. #include "lynx_split.h"
  349. #include <tuple>
  350. int lynxSplitFailures = 0;
  351. int lynxSplitChecks = 0;
  352. std::string lynxSplitFlpDir;
  353. static std::vector<std::tuple<int, const char*, void (*)()>>& lynxSplitPending()
  354. {
  355. static std::vector<std::tuple<int, const char*, void (*)()>> p;
  356. return p;
  357. }
  358. void lynxSplitAdd (int index, const char* name, void (*fn)()) { lynxSplitPending().emplace_back (index, name, fn); }
  359. std::vector<std::pair<const char*, std::function<void()>>>& lynxSplitRegistry()
  360. {
  361. // called from main() only (after every chunk registered its tests): the single-TU order
  362. static std::vector<std::pair<const char*, std::function<void()>>> r;
  363. if (r.empty())
  364. {
  365. auto p = lynxSplitPending();
  366. std::sort (p.begin(), p.end(), [] (const auto& a, const auto& b) { return std::get<0> (a) < std::get<0> (b); });
  367. for (auto& [index, name, fn] : p)
  368. r.emplace_back (name, fn);
  369. }
  370. return r;
  371. }
  372. ''')
  373. # stale chunks of an earlier, bigger N
  374. for f in os.listdir(out):
  375. m = re.match(r"chunk(\d+)\.cpp$", f)
  376. if m and int(m.group(1)) >= n:
  377. os.remove(os.path.join(out, f))
  378. print("split-tests: %d tests in %d chunks (%d inline definitions)" % (len(tests), n, len(edits_inline)))
  379. if __name__ == "__main__":
  380. main()