#!/usr/bin/env python3 """Generate voidlink/symlib_table.cpp from data/symlib_{linux,windows,macos}.txt. Usage: python3 tools/gen_symlib_table.py # from project root python3 tools/gen_symlib_table.py --check # verify .cpp is up-to-date; exit 1 if not The .txt format: one entry per line — "symbol library" whitespace-separated. Lines beginning with # are comments. Entries MUST be sorted by symbol name. """ import sys import os import re import argparse from pathlib import Path SCRIPT_DIR = Path(__file__).parent PROJECT_ROOT = SCRIPT_DIR.parent DATA_DIR = PROJECT_ROOT / "data" OUT_FILE = PROJECT_ROOT / "voidlink" / "symlib_table.cpp" PLATFORMS = [ ("linux", "linux_table", DATA_DIR / "symlib_linux.txt"), ("windows", "windows_table", DATA_DIR / "symlib_windows.txt"), ("macos", "macos_table", DATA_DIR / "symlib_macos.txt"), ] HEADER = """\ // Per-OS symbol → import library table. // Generated from data/symlib_{linux,windows,macos}.txt — edit those files, // then run: python3 tools/gen_symlib_table.py // Arrays MUST remain sorted by first field (symbol name) for binary search. #include "symlib_table.hpp" #include "format/vlc_format.hpp" #include #include #include using namespace std::string_view_literals; namespace { struct Entry { std::string_view name; std::string_view library; }; """ FOOTER = """\ template static std::string_view lookup(const Table& table, std::string_view name) { auto it = std::lower_bound( table.begin(), table.end(), name, [](const Entry& e, std::string_view n) { return e.name < n; }); if (it != table.end() && it->name == name) return it->library; return {}; } } // namespace namespace voidlibc::voidlink { std::string_view library_for(voidlibc::format::TargetOS os, std::string_view name) { using voidlibc::format::TargetOS; switch (os) { case TargetOS::Linux: return lookup(linux_table, name); case TargetOS::Windows: return lookup(windows_table, name); case TargetOS::MacOS: return lookup(macos_table, name); default: return {}; } } std::string_view default_library(voidlibc::format::TargetOS os) { using voidlibc::format::TargetOS; switch (os) { case TargetOS::Linux: return "libc.so.6"; case TargetOS::Windows: return "ucrtbase.dll"; case TargetOS::MacOS: return "/usr/lib/libSystem.B.dylib"; default: return ""; } } } // namespace voidlibc::voidlink """ def parse_txt(path: Path) -> list[tuple[str, str]]: """Parse a symlib .txt file and return entries sorted by symbol name. Entries within sections may be sorted locally but not globally. The generator sorts them globally for the constexpr binary-search array. """ entries = [] seen: dict[str, str] = {} for lineno, raw in enumerate(path.read_text().splitlines(), 1): line = raw.strip() if not line or line.startswith("#"): continue parts = line.split() if len(parts) != 2: sys.exit(f"{path}:{lineno}: expected 'symbol library', got: {raw!r}") sym, lib = parts if sym in seen: sys.exit(f"{path}:{lineno}: duplicate symbol '{sym}' (previous: {seen[sym]})") seen[sym] = lib entries.append((sym, lib)) entries.sort(key=lambda x: x[0]) return entries def format_table(var_name: str, label: str, entries: list[tuple[str, str]]) -> str: if not entries: return f"static constexpr std::array {var_name}{{}};\n" name_width = max(len(sym) for sym, _ in entries) + 2 # +2 for quotes lines = [f"// ── {label} {'─' * max(0, 77 - len(label))}\n"] lines.append(f"static constexpr std::array {var_name} = {{\n") for sym, lib in entries: quoted_sym = f'"{sym}"' lines.append(f" Entry{{{quoted_sym:<{name_width}}, \"{lib}\"}},\n") lines.append("};\n\n") return "".join(lines) def generate() -> str: parts = [HEADER] for label, var_name, txt_path in PLATFORMS: entries = parse_txt(txt_path) parts.append(format_table(var_name, label.capitalize(), entries)) parts.append(FOOTER) return "".join(parts) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--check", action="store_true", help="verify .cpp is current; exit 1 if stale") args = parser.parse_args() content = generate() if args.check: if not OUT_FILE.exists(): print(f"STALE: {OUT_FILE} does not exist", file=sys.stderr) sys.exit(1) current = OUT_FILE.read_text() if current != content: print( f"STALE: {OUT_FILE} differs from generated output.\n" "Run: python3 tools/gen_symlib_table.py", file=sys.stderr, ) sys.exit(1) print(f"OK: {OUT_FILE} is up-to-date") return OUT_FILE.write_text(content) total = sum(len(parse_txt(p)) for _, _, p in PLATFORMS) print(f"Wrote {OUT_FILE} ({total} entries across {len(PLATFORMS)} platforms)") if __name__ == "__main__": main()