aboutsummaryrefslogtreecommitdiff
path: root/generate-flatbuffers.py
blob: fb2f1ac984c4892bab47f29ec64ab4069325a195 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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}Fbs"
                    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-25.2.10", "-o", gen_path, "--java"] + [
                temp_dir / schema_filename
                for schema_filename in schema_filenames
            ],
            check=True,
        )


_main()