-
Notifications
You must be signed in to change notification settings - Fork 76
Expand file tree
/
Copy pathgenerate_import_cache_cpp.py
More file actions
245 lines (193 loc) · 7.06 KB
/
generate_import_cache_cpp.py
File metadata and controls
245 lines (193 loc) · 7.06 KB
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
import json
from pathlib import Path
script_dir = Path(__file__).parent
# Load existing JSON data from a file if it exists
json_data = {}
json_cache_path = Path(script_dir) / "cache_data.json"
try:
json_data = json.loads(Path(json_cache_path).read_text())
except FileNotFoundError:
print("Please first use 'generate_import_cache_json.py' first to generate json")
# deal with leaf nodes?? Those are just PythonImportCacheItem
def get_class_name(path: str) -> str:
parts: list[str] = path.replace("_", "").split(".")
parts = [x.title() for x in parts]
return "".join(parts) + "CacheItem"
def get_filename(name: str) -> str:
return name.replace("_", "").lower() + "_module.hpp"
def get_variable_name(name: str) -> str:
if name in ["short", "ushort"]:
return name + "_"
return name
def collect_items_of_module(module: dict, collection: dict):
global json_data
children = module["children"]
collection[module["full_path"]] = module
for child in children:
collect_items_of_module(json_data[child], collection)
class CacheItem:
def __init__(self, module: dict, items) -> None:
self.name = module["name"]
self.module = module
self.items = items
self.class_name = get_class_name(module["full_path"])
def get_full_module_path(self):
if self.module["type"] != "module":
return ""
full_path = self.module["full_path"]
return f"""
public:
\tstatic constexpr const char *Name = "{full_path}";
"""
def get_optionally_required(self):
if "required" not in self.module:
return ""
string = f"""
protected:
\tbool IsRequired() const override final {{
\t\treturn {str(self.module["required"]).lower()};
\t}}
"""
return string
def get_variables(self):
variables = []
for key in self.module["children"]:
item = self.items[key]
name = item["name"]
var_name = get_variable_name(name)
class_name = "PythonImportCacheItem" if item["children"] == [] else get_class_name(item["full_path"])
variables.append(f"\t{class_name} {var_name};")
return "\n".join(variables)
def get_initializer(self):
variables = []
for key in self.module["children"]:
item = self.items[key]
name = item["name"]
var_name = get_variable_name(name)
if item["children"] == []:
initialization = f'{var_name}("{name}", this)'
variables.append(initialization)
else:
arguments = "" if item["type"] == "module" else "this"
initialization = f"{var_name}({arguments})"
variables.append(initialization)
if self.module["type"] != "module":
constructor_params = f'"{self.name}"'
constructor_params += ", parent"
else:
full_path = self.module["full_path"]
constructor_params = f'"{full_path}"'
return f"PythonImportCacheItem({constructor_params}), " + ", ".join(variables) + "{}"
def get_constructor(self):
if self.module["type"] == "module":
return f"{self.class_name}()"
return f"{self.class_name}(optional_ptr<PythonImportCacheItem> parent)"
def to_string(self):
return f"""
struct {self.class_name} : public PythonImportCacheItem {{
{self.get_full_module_path()}
public:
\t{self.get_constructor()} : {self.get_initializer()}
\t~{self.class_name}() override {{}}
{self.get_variables()}
{self.get_optionally_required()}
}};
"""
def collect_classes(items: dict) -> list:
output: list = []
for item in items.values():
if item["children"] == []:
continue
output.append(CacheItem(item, items))
return output
class ModuleFile:
def __init__(self, module: dict) -> None:
self.module = module
self.file_name = get_filename(module["name"])
self.items = {}
collect_items_of_module(module, self.items)
self.classes = collect_classes(self.items)
self.classes.reverse()
def get_classes(self):
return "".join(item.to_string() for item in self.classes)
def to_string(self):
string = f"""
//===----------------------------------------------------------------------===//
// DuckDB
//
// duckdb_python/import_cache/modules/{self.file_name}
//
//
//===----------------------------------------------------------------------===//
#pragma once
#include "duckdb_python/import_cache/python_import_cache_item.hpp"
//! Note: This class is generated using scripts.
//! If you need to add a new object to the cache you must:
//! 1. adjust scripts/imports.py
//! 2. run python scripts/generate_import_cache_json.py
//! 3. run python scripts/generate_import_cache_cpp.py
//! 4. run pre-commit to fix formatting errors
namespace duckdb {{
{self.get_classes()}
}} // namespace duckdb
"""
return string
files: list[ModuleFile] = []
for value in json_data.values():
if value["full_path"] != value["name"]:
continue
files.append(ModuleFile(value))
for file in files:
content = file.to_string()
path = f"src/duckdb_py/include/duckdb_python/import_cache/modules/{file.file_name}"
import_cache_path = Path(script_dir) / ".." / path
import_cache_path.write_text(content)
def get_root_modules(files: list[ModuleFile]):
modules = []
for file in files:
name = file.module["name"]
class_name = get_class_name(name)
modules.append(f"\t{class_name} {name};")
return "\n".join(modules)
# Generate the python_import_cache.hpp file
# adding all the root modules with their 'name'
import_cache_file = f"""
//===----------------------------------------------------------------------===//
// DuckDB
//
// duckdb_python/import_cache/python_import_cache.hpp
//
//
//===----------------------------------------------------------------------===//
#pragma once
#include "duckdb_python/pybind11/pybind_wrapper.hpp"
#include "duckdb.hpp"
#include "duckdb/common/vector.hpp"
#include "duckdb_python/import_cache/python_import_cache_modules.hpp"
namespace duckdb {{
struct PythonImportCache {{
public:
explicit PythonImportCache() {{
}}
~PythonImportCache();
public:
{get_root_modules(files)}
public:
py::handle AddCache(py::object item);
private:
vector<py::object> owned_objects;
}};
}} // namespace duckdb
"""
import_cache_path = Path(script_dir) / ".." / "src/duckdb_py/include/duckdb_python/import_cache/python_import_cache.hpp"
import_cache_path.write_text(import_cache_file)
def get_module_file_path_includes(files: list[ModuleFile]):
template = '#include "duckdb_python/import_cache/modules/{}"'
return "\n".join(template.format(f.file_name) for f in files)
module_includes = get_module_file_path_includes(files)
modules_header = (
Path(script_dir) / ".." / ("src/duckdb_py/include/duckdb_python/import_cache/python_import_cache_modules.hpp")
)
modules_header.write_text(module_includes)
# Generate the python_import_cache_modules.hpp file
# listing all the generated header files