diff options
| author | Michael Williamson <mike@zwobble.org> | 2026-03-22 09:54:27 +0000 |
|---|---|---|
| committer | Michael Williamson <mike@zwobble.org> | 2026-03-22 10:16:02 +0000 |
| commit | 47442811098a6ed4d8a6ae80f06c13f47451a4d9 (patch) | |
| tree | 4e7549a4816ed082719da49d7ebab10cb91f9b22 /generate-flatbuffers.py | |
| parent | 6e2425bfc5ad9bfac68289a9dcc2cccee1441fd9 (diff) | |
Add flatbuffers schema
Diffstat (limited to 'generate-flatbuffers.py')
| -rw-r--r-- | generate-flatbuffers.py | 56 |
1 files changed, 56 insertions, 0 deletions
diff --git a/generate-flatbuffers.py b/generate-flatbuffers.py new file mode 100644 index 00000000..986e6e8f --- /dev/null +++ b/generate-flatbuffers.py @@ -0,0 +1,56 @@ +import os +import pathlib +import re +import shutil +import subprocess +import tempfile + + +def _main(): + os.chdir(os.path.dirname(__file__)) + + with tempfile.TemporaryDirectory() as temp_dir: + temp_dir = pathlib.Path(temp_dir) + schema_filenames = ["sources.fbs", "patio.fbs"] + namespace_map = {} + type_map = {} + + for schema_filename in schema_filenames: + with open(pathlib.Path("flatbuffers") / schema_filename, "rt") as source_schema_file: + source_schema = list(source_schema_file) + + for line_index, line in enumerate(source_schema): + namespace_match = re.match("^namespace (.*);$", line) + if namespace_match is not None: + source_namespace = namespace_match[1] + dest_namespace = f"org.shedlang.compiler.{source_namespace.lower()}.flatbuffers" + namespace_map[source_namespace] = dest_namespace + source_schema[line_index] = f"namespace {dest_namespace};" + + type_match = re.match(r"^((?:enum|table|union)\s+)(\S+)(\s+.*{)", line) + if type_match is not None: + source_type = type_match[2] + dest_type = f"{source_type}Flatbuffers" + type_map[source_type] = dest_type + source_schema[line_index] = f"{type_match[1]}{dest_type}{type_match[3]}" + + with open(temp_dir / schema_filename, "wt") as dest_schema_file: + for line in source_schema: + for source_namespace, dest_namespace in namespace_map.items(): + line = line.replace(f":{source_namespace}.", f":{dest_namespace}.") + for source_type, dest_type in type_map.items(): + line = re.sub(rf"\b{source_type}\b", dest_type, line) + + dest_schema_file.write(line) + + gen_path = pathlib.Path("src/gen/java") + subprocess.run( + ["flatc", "-o", gen_path, "--java"] + [ + temp_dir / schema_filename + for schema_filename in schema_filenames + ], + check=True, + ) + + +_main() |
