-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathEnvironment.py
355 lines (292 loc) · 10.8 KB
/
Environment.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
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
# -*- coding: utf-8 -*-
# cython: language_level = 3
"""
提供, 维护编译时环境
"""
import ast
import json
import os
import warnings
from typing import Any
from typing import override
from ABCTypes import ABCEnvironment
from BreakPointTools import SplitBreakPoint
from Configuration import CompileConfiguration
from Configuration import GlobalConfiguration
from DebuggingTools import FORCE_COMMENT
from DefaultCodeGenerators import DefaultCodeGenerators
from NamespaceTools import FileNamespace
from NamespaceTools import Namespace
from NamespaceTools import join_file_ns
class SBPWrapper(SplitBreakPoint):
"""
小改SplitBreakPoint, 打个广告
"""
def _copyright(self) -> None:
self._write2file(self._env.COMMENT(f"Generated by MCFC"))
self._write2file(self._env.COMMENT(f"Github: https://github.com/C418-11/MinecraftFunctionCompiler"))
self._write2file(self._env.COMMENT(f"================================================================="))
self._write2file('\n')
@override
def _parse_comment(self, text: str) -> bool:
result = super()._parse_comment(text)
if result:
self._copyright()
return result
@override
def open(self) -> None:
super().open()
self._copyright()
class Environment(ABCEnvironment):
"""
编译环境
文档详见 ABCEnvironment
.. seealso::
:class:`ABC.ABCEnvironment`
"""
def __init__(self, c_conf: CompileConfiguration, g_conf: GlobalConfiguration = None):
super().__init__(c_conf, g_conf)
self.namespace = Namespace(self.c_conf.base_namespace)
self.file_namespace = FileNamespace()
self.code_generators = DefaultCodeGenerators.copy()
@override
def generate_code(self, node: Any, namespace: str, file_namespace: str) -> str:
try:
generator_info = self.code_generators[type(node)]
except KeyError:
warnings.warn(f"无法解析的节点: {namespace}.{type(node).__name__}", UserWarning)
err_msg = json.dumps({"text": f"无法解析的节点: {namespace}.{type(node).__name__}", "color": "red"})
return f"tellraw @a {err_msg}\n" + self.COMMENT("无法解析的节点:") + self.COMMENT(ast.dump(node, indent=4))
code_generator = generator_info["func"]
params_data = {
"namespace": namespace,
"file_namespace": file_namespace,
"node": node,
"env": self,
"c_conf": self.c_conf,
"g_conf": self.g_conf
}
required_params = generator_info["params"] & set(params_data.keys())
required_data = {k: params_data[k] for k in required_params}
try:
result = code_generator(**required_data)
except CompileFailedException as err:
if not hasattr(node, "lineno"):
raise
c_traceback = _build_compile_traceback(self.c_conf, namespace, file_namespace, node)
err.add_traceback(c_traceback)
raise
except Exception as err:
new_exception = CompileFailedException(err)
if hasattr(node, "lineno"):
c_traceback = _build_compile_traceback(self.c_conf, namespace, file_namespace, node)
new_exception.add_traceback(c_traceback)
raise new_exception
if result is None:
result = ''
return result
@override
def ns_split_base(self, namespace: str) -> tuple[str, str]:
return self.namespace.split_base(namespace)
@override
def ns_join_base(self, name: str) -> str:
return self.namespace.join_base(name)
@override
def ns_from_node(
self,
node: Any,
namespace: str,
*,
not_exists_ok: bool = False,
ns_type: str | None = None
) -> tuple[str, str, str]:
return self.namespace.node_to_namespace(node, namespace, not_exists_ok=not_exists_ok, ns_type=ns_type)
@override
def ns_init(self, namespace: str, ns_type: str) -> None:
self.namespace.init_root(namespace, ns_type)
@override
def ns_setter(self, name: str, targe_namespace: str, namespace: str, ns_type: str) -> None:
self.namespace.setter(name, targe_namespace, namespace, ns_type)
@override
def ns_getter(self, name, namespace: str, ret_raw: bool = False) -> tuple[str | dict, str]:
return self.namespace.getter(name, namespace, ret_raw)
@override
def ns_store_local(self, namespace: str) -> tuple[str, str]:
return self.namespace.store_local(self.g_conf, self.COMMENT, namespace)
@override
def temp_ns_init(self, namespace: str) -> None:
self.namespace.init_temp(namespace)
@override
def temp_ns_append(self, namespace: str, name: str) -> None:
self.namespace.append_temp(namespace, name)
@override
def temp_ns_remove(self, namespace: str, name: str) -> None:
self.namespace.remove_temp(namespace, name)
@override
def file_ns_init(self, file_namespace: str, level: str | None, file_ns_type: str, ns: str) -> None:
self.file_namespace.init_root(file_namespace, level, file_ns_type, ns)
@override
def file_ns_setter(
self,
name: str,
targe_file_namespace: str,
file_namespace: str,
level: str | None,
file_ns_type: str, ns: str
) -> None:
self.file_namespace.setter(name, targe_file_namespace, file_namespace, level, file_ns_type, ns)
@override
def file_ns_getter(self, name, file_namespace: str, ret_raw: bool = False) -> tuple[str | dict, str]:
return self.file_namespace.getter(name, file_namespace, ret_raw)
@override
def file_ns2path(self, path: str, *args: str) -> str:
return os.path.normpath(os.path.join(self.c_conf.SAVE_PATH, path, *args))
@override
def mkdirs_file_ns(self, file_namespace: str, *args: str) -> None:
f_ns = join_file_ns(file_namespace, *args)
os.makedirs(self.file_ns2path(f_ns), exist_ok=True)
@override
def writeable_file_namespace(self, file_namespace: str, namespace: str) -> SBPWrapper:
return SBPWrapper(
self,
self.c_conf,
self.g_conf,
self.file_ns2path(file_namespace),
namespace,
encoding=self.c_conf.Encoding
)
@override
def COMMENT(self, *texts: str, **kv_texts: str) -> str:
if not self.c_conf.GENERATE_COMMENTS:
return ''
return FORCE_COMMENT(*texts, **kv_texts)
class CompileTraceback:
"""
保存编译过程中的追踪信息
"""
def __init__(
self,
source_file_path: str,
lineno: int,
end_lineno: int,
col_offset: int,
end_col_offset: int,
namespace: str,
file_namespace: str
) -> None:
"""
初始化
:param source_file_path: 正在编译的源码文件绝对路径
:type source_file_path: str
:param lineno: 正在编译的源码起始行号
:type lineno: int
:param end_lineno: 正在编译的源码结束行号
:type end_lineno: int
:param col_offset: 正在编译的源码起始列号
:type col_offset: int
:param end_col_offset: 正在编译的源码结束列号
:type end_col_offset: int
:param namespace: 编译源码所在的命名空间
:type namespace: str
:param file_namespace: 编译源码所在的文件命名空间
:type file_namespace: str
:return: None
:rtype: None
"""""
self.source_file_path = source_file_path
self.lineno = lineno
self.end_lineno = end_lineno
self.col_offset = col_offset
self.end_col_offset = end_col_offset
self.namespace = namespace
self.file_namespace = file_namespace
self.code_lines: list[str] = []
self.code_columns: list[str] = []
def init(self, env: Environment):
"""
初始化
:param env: 运行环境
:type env: Environment
:return: None
:rtype: None
"""
code_lines = ''
with open(self.source_file_path, mode='r', encoding=env.c_conf.Encoding) as f:
for i, line in enumerate(f, start=1):
if (i < self.lineno) or (i > self.end_lineno):
continue
code_lines += line
self.code_lines = code_lines.split('\n')[:-1]
self.code_columns = code_lines[self.col_offset:self.end_col_offset].split('\n')
def _file_namespace2source_file(c_conf: CompileConfiguration, file_namespace: str) -> str:
"""
将文件命名空间转换为源码文件绝对路径
:param c_conf: 编译配置
:type c_conf: CompileConfiguration
:param file_namespace: 文件命名空间
:type file_namespace: str
:return: 源码文件绝对路径
:rtype: str
"""
root_f_ns = file_namespace.split('\\', 1)[0]
source_file_path = os.path.join(c_conf.READ_PATH, root_f_ns)
source_file = f"{source_file_path}.py"
abs_source_file = os.path.abspath(source_file)
return abs_source_file
def _build_compile_traceback(
c_conf: CompileConfiguration, namespace, file_namespace: str, node: Any) -> CompileTraceback:
"""
构建编译追踪信息
:param c_conf: 编译配置
:type c_conf: CompileConfiguration
:param namespace: 命名空间
:type namespace: str
:param file_namespace: 文件命名空间
:type file_namespace: str
:param node: 正在编译的AST节点
:type node: Any
:return: 编译追踪信息
:rtype: CompileTraceback
"""
source_file_path = _file_namespace2source_file(c_conf, file_namespace)
c_traceback = CompileTraceback(
source_file_path,
node.lineno,
node.end_lineno,
node.col_offset,
node.end_col_offset,
namespace,
file_namespace,
)
return c_traceback
class CompileFailedException(Exception):
"""
编译失败异常
"""
def __init__(self, raw_exc: BaseException) -> None:
"""
初始化
:param raw_exc: 原始异常
:type raw_exc: BaseException
:return: None
:rtype: None
"""
self._raw_exc = raw_exc
self.traceback: list[CompileTraceback] = []
@property
def raw_exc(self) -> BaseException:
return self._raw_exc
def add_traceback(self, _traceback: CompileTraceback) -> None:
"""
添加追踪信息
:param _traceback: 追踪信息
:type _traceback: CompileTraceback
:return: None
:rtype: None
"""
self.traceback.append(_traceback)
__all__ = (
"CompileTraceback",
"CompileFailedException",
"Environment",
)