#!/usr/bin/env python3 """Generate C++ format constants from the public dictionary format contract.""" import argparse import json from pathlib import Path root = Path(__file__).resolve().parent spec = json.loads((root / 'format.json').read_text()) rule = spec['quanpin'] expected = '''// Generated by contracts/dictionary/generate.py; edit format.json instead. #pragma once #include #include namespace metasequoia::dictionary_format { inline constexpr int version = VERSION; inline constexpr std::size_t maximum_numbered_syllables = MAXIMUM; inline constexpr char initials[] = INITIALS; inline std::string quanpin_table(std::size_t syllables, char initial) { if (syllables == 0 || initial < 'a' || initial > 'z') return {}; return std::string(PREFIX) + (syllables <= maximum_numbered_syllables ? std::to_string(syllables) : OVERFLOW) + "_" + initial; } } // namespace metasequoia::dictionary_format '''.replace('VERSION', str(spec['formatVersion'])).replace('MAXIMUM', str(rule['maximumNumberedSyllables'])) for name, value in [('INITIALS', rule['initials']), ('PREFIX', rule['prefix']), ('OVERFLOW', rule['overflowBucket'])]: expected = expected.replace(name, json.dumps(value)) parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--check', action='store_true') args = parser.parse_args() target = root / 'format.h' if args.check: if not target.exists() or target.read_text() != expected: raise SystemExit('Dictionary format header is stale; run contracts/dictionary/generate.py') else: target.write_text(expected)