-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparsers.py
204 lines (184 loc) · 7.41 KB
/
parsers.py
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
import json
import pathlib
import os
import re
OUTPUT_DIR = "out"
os.makedirs(OUTPUT_DIR, exist_ok=True)
def parse_type(type_name) -> str:
__types = {
"void": "nil",
None: "nil",
"int": "integer",
"bool": "boolean",
"[]": "table",
"auto": "any"
}
if (type_name in __types.keys()):
return __types[type_name]
return type_name
def parse_file(file: pathlib.Path):
_class = {}
enums = {}
__enum = None
__class = None
function = None
params_w_desc = []
example = ""
group = ""
description = ""
lookback_ref = []
with open(file) as f:
for _, line in (line_enum := enumerate(f)):
lookback_ref.append(line.strip())
line = line.strip()
if line.startswith("class"):
__class = line.split(" ")[1].strip("{").strip()
_class[__class] = {}
continue
if line.startswith("enum "):
__enum = line.split(" ")[1].strip("{").strip()
enums[__enum] = {
"params": [],
"desc": "*".join(lookback_ref[2].strip().split("*")[1:]).strip(),
}
lookback_ref = []
if __enum:
text = ""
while True:
_, text = next(line_enum)
text = text.strip()
if text == "};":
break
enums[__enum]["params"].append(
{
"param": text.strip().split(" ")[0].strip(",").strip(),
"desc": text.strip().split("//!<")[1].strip(),
}
)
__enum = None
continue
if __class:
lookback_ref = [] # we don't need to store previous lines for classes
if line.startswith("/**"):
_, description = next(line_enum)
description = "*".join(description.strip().split("*")[1:]).strip()
continue
if line.startswith("* \\ingroup"):
group = line.split(" ")[2]
continue
if line.startswith("* @code"):
_text = ""
while True:
_, text = next(line_enum)
text = text.strip()
if text.startswith("* @endcode"):
break
_text += "*".join(text.split("*")[1:]).strip() + "\n"
example = _text
continue
if line.startswith("* @param"):
raw = line.split(" ")
param = raw[2]
desc = " ".join(raw[4:])
optional = False
if "<b>(optional)</b>" in desc.lower():
optional = True
desc = desc.strip("<b>(optional)</b>").strip()
params_w_desc.append(
{
"param": param,
"desc": desc,
"type": "any",
"optional": optional,
}
)
if line.startswith("*/"):
_, raw_line = next(line_enum)
pattern = r"(\w+)\s+(\w+)\(([^)]*)\);"
matches = re.match(pattern, raw_line.strip())
if matches:
return_type = matches.group(1)
function = matches.group(2)
arguments = matches.group(3)
argument_list = [arg.strip() for arg in arguments.split(",")]
params = []
for arg in argument_list:
if arg != "void" and arg != [""] and arg:
type_name, param_name = arg.split()
type_name = parse_type(type_name)
param = {
"param": param_name,
"desc": "",
"type": type_name,
"optional": False,
}
params.append(param)
for i in params:
for j in params_w_desc:
if j["param"] == i["param"]:
i["desc"] = j["desc"]
i["optional"] = j["optional"]
else:
continue
_class[__class][function] = {
"params": params,
"return_type": return_type,
"example": example,
"group": group,
"description": description,
}
function = None
params = []
example = ""
group = ""
description = ""
params_w_desc = []
if _class:
return _class, enums
def generate_lua_code(
parsed_source: dict[str, dict[str, dict[str, None | str | list]]]
):
lua_source = "-- lpp-vita lua source code\n\n"
for enum, items in parsed_source["enums"].items():
lua_source += "---\n"
lua_source += f"---{items['desc']}\n"
lua_source += "---\n"
lua_source += f"{enum} = " + "{\n"
for value, e_param in enumerate(items["params"]):
lua_source += f" --- {e_param['desc']}\n"
lua_source += (
f" {e_param['param']} = {value}"
+ ("," if value != len(items["params"]) - 1 else "")
+ "\n"
)
lua_source += "}\n\n"
for _class, methods in parsed_source["classes"].items():
lua_source += f"{_class} = " + "{}\n\n"
for function, metadata in methods.items():
lua_source += "---\n"
lua_source += f"---{metadata['description']}\n"
lua_source += "---\n"
lua_source += "---\n"
lua_source += "---\n"
params = "("
for param in metadata["params"]:
if param:
lua_source += f"---@param {param['param']}{'?' if param['optional'] else ''} {param['type']} {param['desc']}\n"
params += f"{param['param']}, "
params = params.strip(", ") + ")"
return_type = metadata["return_type"]
return_type = parse_type(return_type)
lua_source += f"---@return {return_type}\n"
lua_source += f"function {_class}.{function}{params} end\n\n"
return lua_source
directory_path = pathlib.Path(__file__).parent / "lpp-vita" / "doc"
parsed_classes = {"classes": {}, "enums": {}}
for file in directory_path.glob("*.cpp"):
classes, enums = parse_file(file)
parsed_classes["classes"].update(classes)
parsed_classes["enums"].update(enums)
with open(os.path.join(OUTPUT_DIR, "parsed.json"), "w") as f:
f.write(json.dumps(parsed_classes, indent=4, ensure_ascii=False))
lua_source = generate_lua_code(parsed_classes)
with open(os.path.join(OUTPUT_DIR, "lpp-vita.lua"), "w") as f:
f.write(lua_source)