pyscreeps-arena 0.3.0__py3-none-any.whl → 0.5.4a0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1225 @@
1
+ import os.path
2
+
3
+ from pyscreeps_arena.core import *
4
+ from pyscreeps_arena.localization import *
5
+
6
+ import re
7
+ import shutil
8
+ import chardet
9
+ import subprocess
10
+ import pyperclip
11
+ from colorama import Fore
12
+
13
+ WAIT = Fore.YELLOW + ">>>" + Fore.RESET
14
+ GREEN = Fore.GREEN + "{}" + Fore.RESET
15
+ python_version_info = sys.version_info
16
+ python_version_info = f"{python_version_info.major}.{python_version_info.minor}.{python_version_info.micro}"
17
+
18
+
19
+ def replace_src_prefix(file_list):
20
+ """
21
+ 将列表中以'./src.'开头的字符串替换为'./'
22
+
23
+ 参数:
24
+ file_list: 字符串列表
25
+
26
+ 返回:
27
+ 替换后的新列表
28
+ """
29
+ _ = []
30
+
31
+ for item in file_list:
32
+ if isinstance(item, str) and item.startswith('./src.'):
33
+ _new = item.replace('./src.', './', 1)
34
+ if _new in file_list:
35
+ continue
36
+ _.append(item)
37
+
38
+ return _
39
+
40
+ # def InsertPragmaBefore(content:str) -> str:
41
+ # """
42
+ # 在content的开头插入__pragma__('noalias', 'undefined')等内容 |
43
+ # Insert __pragma__('noalias', 'undefined') at the beginning of content
44
+ # :param content: str
45
+ # :return: str
46
+ # """
47
+ # return PYFILE_PRAGMA_INSERTS + "\n" + content
48
+ class Compiler_Const:
49
+ PROTO_DEFINES_DIRS = ["builtin", "library"]
50
+ FILE_STRONG_REPLACE = {
51
+ "std": {
52
+ "==": "===",
53
+ "!=": "!==",
54
+ }
55
+ }
56
+ PYFILE_IGNORE_CHECK_FNAMES = ['builtin/const.py', 'builtin/proto.py', 'builtin/utils.py']
57
+
58
+ PYFILE_PRAGMA_INSERTS = """
59
+ # __pragma__('noalias', 'undefined')
60
+ # __pragma__('noalias', 'Infinity')
61
+ # __pragma__('noalias', 'clear')
62
+ # __pragma__('noalias', 'get')
63
+ """
64
+
65
+ TOTAL_INSERT_AT_HEAD = """
66
+ import { createConstructionSite, findClosestByPath, findClosestByRange, findInRange, findPath, getCpuTime, getDirection, getHeapStatistics, getObjectById, getObjects, getObjectsByPrototype, getRange, getTerrainAt, getTicks,} from 'game/utils';
67
+ import { ConstructionSite as GameConstructionSite, Creep as GameCreep, GameObject as GameObjectProto, OwnedStructure, Resource as GameResource, Source as GameSource, Structure as GameStructure, StructureContainer as GameStructureContainer, StructureExtension as GameStructureExtension, StructureRampart as GameStructureRampart, StructureRoad as GameStructureRoad, StructureSpawn as GameStructureSpawn, StructureWall as GameStructureWall, StructureTower as GameStructureTower, Flag as GameFlag} from 'game/prototypes';
68
+ import { ATTACK, ATTACK_POWER, BODYPART_COST, BODYPART_HITS, BOTTOM, BOTTOM_LEFT, BOTTOM_RIGHT, BUILD_POWER, CARRY, CARRY_CAPACITY, CONSTRUCTION_COST, CONSTRUCTION_COST_ROAD_SWAMP_RATIO, CONSTRUCTION_COST_ROAD_WALL_RATIO, CONTAINER_CAPACITY, CONTAINER_HITS, CREEP_SPAWN_TIME, DISMANTLE_COST, DISMANTLE_POWER, ERR_BUSY, ERR_FULL, ERR_INVALID_ARGS, ERR_INVALID_TARGET, ERR_NAME_EXISTS, ERR_NOT_ENOUGH_ENERGY, ERR_NOT_ENOUGH_EXTENSIONS, ERR_NOT_ENOUGH_RESOURCES, ERR_NOT_FOUND, ERR_NOT_IN_RANGE, ERR_NOT_OWNER, ERR_NO_BODYPART, ERR_NO_PATH, ERR_TIRED, EXTENSION_ENERGY_CAPACITY, EXTENSION_HITS, HARVEST_POWER, HEAL, HEAL_POWER, LEFT, MAX_CONSTRUCTION_SITES, MAX_CREEP_SIZE, MOVE, OBSTACLE_OBJECT_TYPES, OK, RAMPART_HITS, RAMPART_HITS_MAX, RANGED_ATTACK, RANGED_ATTACK_DISTANCE_RATE, RANGED_ATTACK_POWER, RANGED_HEAL_POWER, REPAIR_COST, REPAIR_POWER, RESOURCES_ALL, RESOURCE_DECAY, RESOURCE_ENERGY, RIGHT, ROAD_HITS, ROAD_WEAROUT, SOURCE_ENERGY_REGEN, SPAWN_ENERGY_CAPACITY, SPAWN_HITS, STRUCTURE_PROTOTYPES, TERRAIN_PLAIN, TERRAIN_SWAMP, TERRAIN_WALL, TOP, TOP_LEFT, TOP_RIGHT, TOUGH, TOWER_CAPACITY, TOWER_COOLDOWN, TOWER_ENERGY_COST, TOWER_FALLOFF, TOWER_FALLOFF_RANGE, TOWER_HITS, TOWER_OPTIMAL_RANGE, TOWER_POWER_ATTACK, TOWER_POWER_HEAL, TOWER_POWER_REPAIR, TOWER_RANGE, WALL_HITS, WALL_HITS_MAX, WORK} from 'game/constants';
69
+
70
+ import {arenaInfo} from "game";
71
+ import {Visual} from "game/visual"
72
+ import {searchPath, CostMatrix} from "game/path-finder"
73
+ """
74
+
75
+ TOTAL_INSERT_BEFORE_MAIN = """
76
+ """
77
+
78
+ TOTAL_APPEND_ATEND = """
79
+ export var sch = Scheduler();
80
+ var monitor = Monitor(1);
81
+ know.now = 0;
82
+
83
+ StageMachineLogicMeta.__types__ = []; // 清空js首次构造时引入的数据
84
+ __init_before_k__();
85
+ let knowCost = 0;
86
+ let monitorCost = 0;
87
+ let stepCost = 0;
88
+ let timeLine = 0;
89
+ export var loop = function () {
90
+ get.handle();
91
+ know.now = get.now;
92
+ timeLine = get.cpu_us();
93
+ know.handle();
94
+ knowCost = get.cpu_us() - timeLine;
95
+ if (know.now === 1) {
96
+ std.show_welcome();
97
+ init (know);
98
+
99
+ }
100
+
101
+ timeLine = get.cpu_us();
102
+ monitor.handle();
103
+ monitorCost = get.cpu_us() - timeLine;
104
+ for (const creep of get.creeps()){
105
+ creep.handle();
106
+ }
107
+ step (know);
108
+ timeLine = get.cpu_us();
109
+ if (get._SCH_FLAG) sch.handle();
110
+ stepCost = get.cpu_us() - timeLine;
111
+ std.show_usage ();
112
+ print("knowCost:", knowCost, "monitorCost:", monitorCost, "stepCost:", stepCost);
113
+ };
114
+ """
115
+
116
+ TOTAL_SIMPLE_REPLACE_WITH = {
117
+ }
118
+
119
+ PYFILE_WORD_WARNING_CHECK = {
120
+ r"\.\s*get\s*\(": LOC_PYFILE_WORD_WARNING_CHECK_GET,
121
+ r"import\s+math\s*": LOC_PYFILE_WORD_WARNING_CHECK_MATH,
122
+ r"\.\s*clear\s*\(": LOC_PYFILE_WORD_WARNING_CHECK_CLEAR,
123
+ r"\[\s*-\s*1\s*\]": LOC_PYFILE_WORD_WARNING_INDEX_MINUS_ONE,
124
+ }
125
+
126
+ PYFILE_EXIST_WARNING_CHECK = {
127
+ r"__pragma__\s*\(\s*['\"]noalias['\"]\s*,\s*['\"]undefined['\"]\s*\)": "Strongly suggest to add '__pragma__('noalias', 'undefined')'.",
128
+ r"__pragma__\s*\(\s*['\"]noalias['\"]\s*,\s*['\"]Infinity['\"]\s*\)": "Strongly suggest to add '__pragma__('noalias', 'Infinity')'.",
129
+ r"__pragma__\s*\(\s*['\"]noalias['\"]\s*,\s*['\"]clear['\"]\s*\)": "Strongly suggest to add '__pragma__('noalias', 'clear')'.",
130
+ r"__pragma__\s*\(\s*['\"]noalias['\"]\s*,\s*['\"]get['\"]\s*\)": "Strongly suggest to add '__pragma__('noalias', 'get')'.",
131
+ }
132
+
133
+ JS_VM = "org.transcrypt.__runtime__.js"
134
+
135
+ BUILTIN_TRANS = ["engine.js", "stage.js"] # 记录buildin中会被transcrypt的文件
136
+ OTHER_IGNORE_WITH = "./builtin"
137
+
138
+ JS_IMPORT_PAT = re.compile(r'from\s+[\'\"]([^\']+)[\'\"]')
139
+ JS_EXPORT_PAT = re.compile(r'export\s+{([^}]+)}')
140
+ PY_IMPORT_PAT = re.compile(r'from\s+(.+)(?=\s+import)\s+import\s+\*')
141
+ INSERT_PAT = re.compile(r'#\s*insert\s+([^\n]*)') # 因为被判定的string为单line,所以不需要考虑多行的情况
142
+
143
+ TRANSCRYPT_ERROR_REPLACE = {
144
+ # 由于transcrypt的问题,导致编译后的js代码中存在一些错误,需要进行替换
145
+ r"new\s+set\s*\(": r"set(",
146
+ }
147
+
148
+ ARENA_IMPORTS_GETTER = {
149
+ const.ARENA_GREEN: lambda: f"""
150
+ const ARENA_COLOR_TYPE = "green";
151
+ class GameAreaEffect{{
152
+ constructor(){{
153
+ }}
154
+ }};
155
+ class GameConstructionBoost{{
156
+ constructor(){{
157
+ }}
158
+ }};
159
+ import {{ Portal as GamePortal}} from 'arena/season_{config.season}/{const.ARENA_GREEN}/{"advanced" if config.level in ["advance", "advanced"] else "basic"}/prototypes';
160
+
161
+ """,
162
+ const.ARENA_BLUE: lambda: f"""
163
+ const ARENA_COLOR_TYPE = "BLUE";
164
+ const GameScoreCollector = GameStructureSpawn;
165
+ class GameAreaEffect{{
166
+ constructor(){{
167
+ }}
168
+ }};
169
+ class GamePortal{{
170
+ constructor(){{
171
+ }}
172
+ }};
173
+ class GameConstructionBoost{{
174
+ constructor(){{
175
+ }}
176
+ }};
177
+ """,
178
+ const.ARENA_RED: lambda: f"""
179
+ const ARENA_COLOR_TYPE = "RED";
180
+ class GamePortal{{
181
+ constructor(){{
182
+ }}
183
+ }};
184
+ import {{ ConstructionBoost as GameConstructionBoost, AreaEffect as GameAreaEffect }} from 'arena/season_{config.season}/{const.ARENA_RED}/{"advanced" if config.level in ["advance", "advanced"] else "basic"}/prototypes';
185
+ import {{ EFFECT_CONSTRUCTION_BOOST, EFFECT_SLOWDOWN }} from 'arena/season_{config.season}/{const.ARENA_RED}/{"advanced" if config.level in ["advance", "advanced"] else "basic"}/constants';
186
+
187
+ """,
188
+ const.ARENA_GRAY: lambda: f"""
189
+ const ARENA_COLOR_TYPE = "GRAY";
190
+ class GameAreaEffect{{
191
+ constructor(){{
192
+ }}
193
+ }};
194
+ class GamePortal{{
195
+ constructor(){{
196
+ }}
197
+ }};
198
+ class GameConstructionBoost{{
199
+ constructor(){{
200
+ }}
201
+ }};
202
+ let GameFlag = GameStructureSpawn;
203
+ import * as GAME_PROTO_MODULE from 'game/prototypes';
204
+ if (GAME_PROTO_MODULE.Flag){{
205
+ GameFlag = GAME_PROTO_MODULE.Flag;
206
+ }}
207
+ """,
208
+ }
209
+
210
+
211
+ class Compiler_Utils(Compiler_Const):
212
+ last_output = False # 一个小标志位,我只想输出一次此类告警信息
213
+
214
+ @staticmethod
215
+ def auto_read(fpath: str) -> str:
216
+ """
217
+ 读取文件内容,自动应用编码
218
+ :param fpath: str 文件路径
219
+ """
220
+ if not os.path.exists(fpath):
221
+ if not Compiler_Utils.last_output:
222
+ Compiler_Utils.last_output = True
223
+ print()
224
+ core.warn('Compiler_Utils.auto_read', core.lformat(LOC_FILE_NOT_EXISTS, ["", fpath]), end='', head='\n', ln=config.language)
225
+ return ""
226
+
227
+ try:
228
+ with open(fpath, 'r', encoding='utf-8') as f:
229
+ return f.read()
230
+ except UnicodeDecodeError:
231
+ try:
232
+ with open(fpath, 'r', encoding='gbk') as f:
233
+ return f.read()
234
+ except UnicodeDecodeError:
235
+ # 如果使用检测到的编码读取失败,尝试使用chardet检测编码
236
+ with open(fpath, 'rb') as f: # 以二进制模式打开文件
237
+ raw_data = f.read() # 读取文件的原始数据
238
+ result = chardet.detect(raw_data) # 使用chardet检测编码
239
+ encoding = result['encoding'] # 获取检测到的编码
240
+ with open(fpath, 'r', encoding=encoding) as f: # 使用检测到的编码打开文件
241
+ return f.read()
242
+
243
+ def copy_to(self) -> list:
244
+ """
245
+ 复制src到build目录 | copy all files in src to build
246
+ * 注意到src下的文件应当全部为py文件 | all files in src should be py files
247
+ """
248
+ # copy to build dir
249
+ # print(Fore.YELLOW + '>>> ' + Fore.RESET + ' copying to build dir: %s ...' % self.build_dir, end='')
250
+ # LOC_COPYING_TO_BUILD_DIR
251
+
252
+ core.lprint(WAIT, core.lformat(LOC_COPYING_TO_BUILD_DIR, [self.build_dir]), end="", ln=config.language)
253
+
254
+ if os.path.exists(self.build_dir):
255
+ shutil.rmtree(self.build_dir)
256
+ shutil.copytree(self.src_dir, self.build_dir)
257
+ shutil.copytree(self.src_dir, os.path.join(self.build_dir, "src"))
258
+ srcs = [] # src下所有python文件的路径 | paths of all python files under src
259
+ for root, dirs, files in os.walk(self.build_dir):
260
+ for file in files:
261
+ if file.endswith('.py'):
262
+ srcs.append(os.path.join(root, file))
263
+ # add libs
264
+ for lib in self.PROTO_DEFINES_DIRS:
265
+ shutil.copytree(lib, os.path.join(self.build_dir, lib))
266
+
267
+ # overwrite last to [Done]
268
+ # print(Fore.GREEN + '\r[1/6][Done]' + Fore.RESET + ' copying to build dir: %s' % self.build_dir)
269
+
270
+ core.lprint(GREEN.format('[1/6]'), LOC_DONE, " ", core.lformat(LOC_COPYING_TO_BUILD_DIR_FINISH, [self.build_dir]), sep="", head="\r", ln=config.language)
271
+ return srcs
272
+
273
+ @staticmethod
274
+ def potential_check(fpath: str, fname: str) -> bool:
275
+ """
276
+ 检查某个py文件内是否有潜在问题 | check if there are potential problems in a py file
277
+
278
+ 如果有的话,输出[Warn][{file_name}/{line_io}]{detail} | if there are, output [Warn][{file_name}/{line_io}]{detail}
279
+
280
+ Returns:
281
+ bool: 是否有警告
282
+ """
283
+ # 文件路径检查
284
+ # if fpath.endswith('__init__.py') and fpath.find("builtin") == -1:
285
+ # core.error("potential_check", LOC_NOT_SUPPORT_PYFILE_INIT, ln=config.language, ecode=-1, head='\n')
286
+ if fname in Compiler.PYFILE_IGNORE_CHECK_FNAMES:
287
+ return False
288
+
289
+ # # 文件内容检查
290
+ content = Compiler.auto_read(fpath)
291
+ warn_flag = False
292
+ # # 内容关键字检查
293
+ for pat, detail in Compiler.PYFILE_WORD_WARNING_CHECK.items():
294
+ for i, line in enumerate(content.split('\n')):
295
+ m = re.search(pat, line)
296
+ if m:
297
+ # 检查m前面同一行内是否有#,如果有则忽略
298
+ comment = re.search(r'#', line[:m.start()])
299
+
300
+ # 检查m后面同一行内是否有#\s*ignore;,如果有则忽略
301
+ ignore = re.search(r'#\s*>\s*ignore', line[m.end():])
302
+
303
+ if not comment and not ignore:
304
+ warn_flag = True
305
+ core.warn('Compiler.potential_check', f'[{os.path.basename(os.path.dirname(fpath))}/{fname} line:{i + 1}]:', detail, end='', head='\n', ln=config.language)
306
+ return warn_flag
307
+
308
+ @staticmethod
309
+ def preprocess_if_block(source_code: str, variables: dict[str, object]) -> str:
310
+ """
311
+ 预处理if块,将 # > if, # > elif, # > else, # > endif 替换为实际的程序内容 |
312
+ pre-process if blocks by replacing # > if, # > elif, # > else, # > endif with actual code.
313
+ """
314
+ lines = source_code.split('\n') # 按行分割源代码 | split source code into lines
315
+ stack = [] # 初始化一个栈,用于跟踪if条件 | initialize a stack to track if conditions
316
+ result = [] # 初始化一个列表,用于存储处理后的代码行 | initialize a list to store processed code lines
317
+
318
+ for i, line in enumerate(lines): # 遍历源代码的每一行 | iterate over each line of source code
319
+ striped = line.strip() # 去掉行首尾的空格和换行符 | strip leading and trailing whitespace
320
+ # 使用正则表达式匹配不同的条件语句 | use regex to match different conditional statements
321
+ if_match = re.match(r'#\s*>\s*if\s+([^:.]*)$', striped) # 匹配 '# > if' 语句 | match '# > if' statement
322
+ elif_match = re.match(r'#\s*>\s*elif\s+([^:.]*)$', striped) # 匹配 '# > elif' 语句 | match '# > elif' statement
323
+ else_match = re.match(r'#\s*>\s*else$', striped) # 匹配 '# > else' 语句 | match '# > else' statement
324
+ endif_match = re.match(r'#\s*>\s*endif$', striped) # 匹配 '# > endif' 语句 | match '# > endif' statement
325
+
326
+ if if_match: # 如果当前行是 '# > if' 语句 | if it's a '# > if' statement
327
+ condition = if_match.group(1) # 提取条件表达式 | extract the condition expression
328
+ stack.append(eval(condition, variables)) # 评估条件表达式并将其结果压入栈中 | evaluate condition and push result onto stack
329
+ elif elif_match and stack: # 如果当前行是 '# > elif' 语句,并且栈不为空 | if it's a '# > elif' and stack isn't empty
330
+ condition = elif_match.group(1) # 提取条件表达式 | extract the condition expression
331
+ stack[-1] = eval(condition, variables) # 评估条件表达式并更新栈顶 | evaluate condition and update the top of the stack
332
+ elif else_match and stack: # 如果当前行是 '# > else' 语句,并且栈不为空 | if it's a '# > else' and stack isn't empty
333
+ stack[-1] = not stack[-1] # 将栈顶元素取反 | negate the top of the stack
334
+ elif endif_match: # 如果当前行是 '# > endif' 语句 | if it's a '# > endif' statement
335
+ stack.pop() # 弹出栈顶元素 | pop the top of the stack
336
+ else: # 如果当前行不是条件语句 | if it's not a conditional statement
337
+ if not stack or all(stack): # 如果栈为空,或者栈中所有元素均为真 | if stack is empty or all elements are True
338
+ result.append(line) # 将当前行加入结果列表中 | add the current line to the result
339
+
340
+ return '\n'.join(result) # 将处理后的所有代码行连接成一个字符串,并返回最终结果 | join all processed lines into a string and return
341
+
342
+ def expand_folder_imports(self, fpath: str, project_path: str = None):
343
+ """
344
+ 扩展文件夹导入语句:将 `from folder import *` 替换为 `from folder.module import *`
345
+ 仅在文件夹没有 __init__.py 时执行此操作
346
+
347
+ :param fpath: 要处理的文件路径
348
+ :param project_path: 项目根路径,用于解析相对导入,默认为 None(使用文件所在目录)
349
+ """
350
+ if not os.path.exists(fpath):
351
+ return
352
+
353
+ content = self.auto_read(fpath)
354
+ lines = content.split('\n')
355
+ new_lines = []
356
+ changed = False
357
+
358
+ for line in lines:
359
+ m = self.PY_IMPORT_PAT.match(line)
360
+ if not m:
361
+ new_lines.append(line)
362
+ continue
363
+
364
+ original_target = m.group(1)
365
+ target = original_target
366
+ target_path = project_path or os.path.dirname(fpath)
367
+
368
+ # 处理相对路径(向前定位)
369
+ if target.startswith('.'):
370
+ target_path = os.path.dirname(fpath)
371
+ count = 0
372
+ for c in target:
373
+ if c == '.':
374
+ count += 1
375
+ else:
376
+ break
377
+
378
+ # 向上移动目录
379
+ if count > 1:
380
+ for _ in range(count - 1):
381
+ target_path = os.path.dirname(target_path)
382
+
383
+ # 移除开头的点
384
+ target = target[count:]
385
+
386
+ # 如果 target 为空,跳过
387
+ if not target:
388
+ new_lines.append(line)
389
+ continue
390
+
391
+ # 向后定位,构建完整路径
392
+ temp_target = target
393
+ while (_idx := temp_target.find('.')) != -1:
394
+ part = temp_target[:_idx]
395
+ target_path = os.path.join(target_path, part)
396
+ temp_target = temp_target[_idx + 1:]
397
+
398
+ # 最终的文件夹路径
399
+ final_dir_path = os.path.join(target_path, temp_target) if temp_target else target_path
400
+
401
+ # 检查是否是文件夹且没有 __init__.py
402
+ if os.path.isdir(final_dir_path):
403
+ init_path = os.path.join(final_dir_path, '__init__.py')
404
+ if not os.path.exists(init_path):
405
+ # 找到所有 .py 文件(排除 __init__.py)| 如果包含子目录,产生一个警告
406
+ # try:
407
+ # py_files = [f for f in os.listdir(final_dir_path) if f.endswith('.py') and f != '__init__.py']
408
+ # except (FileNotFoundError, PermissionError):
409
+ py_files = []
410
+ for item in os.listdir(final_dir_path):
411
+ _path = os.path.join(final_dir_path, item)
412
+ if os.path.isfile(_path) and item.endswith('.py') and item != '__init__.py':
413
+ py_files.append(item)
414
+ elif os.path.isdir(_path):
415
+ rel = os.path.relpath(final_dir_path, project_path)
416
+ core.warn(f'Compiler.expand_folder_imports', core.lformat(LOC_DIR_UNDER_NONINIT_DIR, [item, rel]), end='', head='\n', ln=config.language )
417
+
418
+
419
+ # 为每个 .py 文件生成导入语句
420
+ if py_files:
421
+ for py_file in py_files:
422
+ module_name = py_file[:-3]
423
+ new_import = f"from {original_target}.{module_name} import *"
424
+ new_lines.append(new_import)
425
+ changed = True
426
+ continue
427
+
428
+ # 保留原行
429
+ new_lines.append(line)
430
+
431
+ # 如果文件有修改,写回
432
+ if changed:
433
+ new_content = '\n'.join(new_lines)
434
+ with open(fpath, 'w', encoding='utf-8') as f:
435
+ f.write(new_content)
436
+
437
+
438
+ def find_chain_import(self, fpath: str, search_dirs: list[str], project_path: str = None, records: dict[str, None] = None) -> list[str]:
439
+ r"""
440
+ 查找文件中的所有import语句,并返回所有import的文件路径 | find all import statements in a file and return the paths of all imported files
441
+ PY_IMPORT_PAT: re.compile(r'\s+from\s+(.+)(?=\s+import)\s+import\s+\*')
442
+ :param fpath: str 目标文件路径 | target file path
443
+ :param search_dirs: list[str] 搜索目录 | search directories
444
+ :param project_path=None: str python项目中的概念,指根文件所在的目录。如果不指定,默认使用第一次调用时给定的fpath,并且稍后的递归会全部使用此路径 |
445
+ concept in python-project, refers to the directory where the root file is located. If not specified, the fpath given at the first call is used by default, and all subsequent recursions will use this path
446
+ :param records=None: dict[str, None] 记录已经查找过的文件路径,避免重复查找 | record the file paths that have been searched to avoid duplicate searches
447
+ """
448
+ if records is None:
449
+ records = {}
450
+ if not os.path.exists(fpath):
451
+ core.error('Compiler.find_chain_import', core.lformat(LOC_FILE_NOT_EXISTS, ["py", fpath]), head='\n', ln=config.language)
452
+ imps = []
453
+ content = self.auto_read(fpath)
454
+ project_path = project_path or os.path.dirname(fpath)
455
+ for no, line in enumerate(content.split('\n')):
456
+ m = self.PY_IMPORT_PAT.match(line)
457
+ if m:
458
+ target = m.group(1)
459
+ target_path = project_path
460
+
461
+ ## 向前定位 | locate forward
462
+ if target.startswith('.'):
463
+ target_path = os.path.dirname(fpath) # 因为使用了相对路径,所以需要先定位到当前文件所在的目录 |
464
+ # because relative path is used, need to locate the directory where the current file is located first
465
+ count = 0
466
+ for c in target:
467
+ if c == '.':
468
+ count += 1
469
+ else:
470
+ break
471
+ if count > 1:
472
+ for _ in range(count - 1):
473
+ target_path = os.path.dirname(target_path)
474
+
475
+ ## 向后定位 | locate backward
476
+ while (_idx := target.find('.')) != -1:
477
+ first_name = target[:_idx]
478
+ target_path = os.path.join(target_path, first_name)
479
+ target = target[_idx + 1:]
480
+
481
+ ## 检查是否存在 | check if exists
482
+ this_path = os.path.join(target_path, target)
483
+ if os.path.isdir(this_path):
484
+ this_path = os.path.join(this_path, '__init__.py')
485
+ else:
486
+ this_path += '.py'
487
+
488
+ if not os.path.exists(this_path):
489
+ core.error('Compiler.find_chain_import', core.lformat(LOC_CHAIN_FILE_NOT_EXISTS, [fpath, no + 1, this_path]), head='\n', ln=config.language)
490
+ if this_path not in records:
491
+ records[this_path] = None
492
+ tmp = self.find_chain_import(this_path, search_dirs, project_path, records) + [this_path]
493
+ imps.extend(tmp)
494
+
495
+ return imps
496
+
497
+ def find_chain_import2(self, fpath: str, search_dirs: list[str], project_path: str = None, records: dict[str, None] = None) -> list[str]:
498
+ r"""
499
+ 查找文件中的所有import语句,并返回所有import的文件路径 | find all import statements in a file and return the paths of all imported files
500
+ PY_IMPORT_PAT: re.compile(r'\s+from\s+(.+)(?=\s+import)\s+import\s+\*')
501
+ :param fpath: str 目标文件路径 | target file path
502
+ :param search_dirs: list[str] 搜索目录 | search directories
503
+ :param project_path=None: str python项目中的概念,指根文件所在的目录。如果不指定,默认使用第一次调用时给定的fpath,并且稍后的递归会全部使用此路径 |
504
+ concept in python-project, refers to the directory where the root file is located. If not specified, the fpath given at the first call is used by default, and all subsequent recursions will use this path
505
+ :param records=None: dict[str, None] 记录已经查找过的文件路径,避免重复查找 | record the file paths that have been searched to avoid duplicate searches
506
+ """
507
+ if records is None:
508
+ records = {}
509
+ if not os.path.exists(fpath):
510
+ core.error('Compiler.find_chain_import', core.lformat(LOC_FILE_NOT_EXISTS, [fpath]), head='\n', ln=config.language)
511
+ imps = []
512
+ content = self.auto_read(fpath)
513
+ project_path = project_path or os.path.dirname(fpath)
514
+
515
+ # 添加根目录和 src 目录到 search_dirs
516
+ root_dir = os.path.dirname(project_path) # 根目录
517
+ src_dir = os.path.join(root_dir, 'src') # src 目录
518
+ if root_dir not in search_dirs:
519
+ search_dirs = [root_dir] + search_dirs
520
+ if src_dir not in search_dirs:
521
+ search_dirs = [src_dir] + search_dirs
522
+
523
+ for no, line in enumerate(content.split('\n')):
524
+ m = self.PY_IMPORT_PAT.match(line)
525
+ if m:
526
+ target = m.group(1)
527
+ target_path = project_path
528
+
529
+ ## 向前定位 | locate forward
530
+ if target.startswith('.'):
531
+ target_path = os.path.dirname(fpath) # 因为使用了相对路径,所以需要先定位到当前文件所在的目录 |
532
+ # because relative path is used, need to locate the directory where the current file is located first
533
+ count = 0
534
+ for c in target:
535
+ if c == '.':
536
+ count += 1
537
+ else:
538
+ break
539
+ if count > 1:
540
+ for _ in range(count - 1):
541
+ target_path = os.path.dirname(target_path)
542
+
543
+ ## 向后定位 | locate backward
544
+ while (_idx := target.find('.')) != -1:
545
+ first_name = target[:_idx]
546
+ target_path = os.path.join(target_path, first_name)
547
+ target = target[_idx + 1:]
548
+
549
+ ## 检查是否存在 | check if exists
550
+ this_path = os.path.join(target_path, target)
551
+ if os.path.isdir(this_path):
552
+ this_path = os.path.join(this_path, '__init__.py')
553
+ else:
554
+ this_path += '.py'
555
+
556
+ if not os.path.exists(this_path):
557
+ # 如果当前路径不存在,尝试在 search_dirs 中查找
558
+ for search_dir in search_dirs:
559
+ search_path = os.path.join(search_dir, target.replace('.', os.sep)) + ('.py' if not os.path.isdir(this_path) else os.sep + '__init__.py')
560
+ if os.path.exists(search_path):
561
+ this_path = search_path
562
+ break
563
+ else:
564
+ core.error('Compiler.find_chain_import', core.lformat(LOC_CHAIN_FILE_NOT_EXISTS, [fpath, no + 1, this_path]), head='\n', ln=config.language)
565
+ if this_path not in records:
566
+ records[this_path] = None
567
+ tmp = self.find_chain_import(this_path, search_dirs, project_path, records) + [this_path]
568
+ imps.extend(tmp)
569
+
570
+ return imps
571
+
572
+ @staticmethod
573
+ def relist_pyimports_to_jsimports(base_dir:str, pyimps:list[str]) -> list[str]:
574
+ """
575
+ 将python的imports路径列表转换为js的imports路径列表 | convert a list of python imports paths to a list of js imports paths
576
+ """
577
+ jsimps = []
578
+ for pyimp in pyimps:
579
+ rel_path_nodes:list[str] = os.path.relpath(pyimp, base_dir).replace('\\', '/').split('/')
580
+ if rel_path_nodes[-1] == '__init__.py':
581
+ rel_path_nodes.pop()
582
+ else:
583
+ rel_path_nodes[-1] = rel_path_nodes[-1][:-3]
584
+ jsimps.append('./' + '.'.join(rel_path_nodes) + '.js')
585
+ return jsimps
586
+
587
+ # ---------- 自定义函数 ---------- #
588
+
589
+ @staticmethod
590
+ def stage_recursive_replace(content: str) -> str:
591
+ """
592
+ 移除 '@recursive' 装饰器行,并在文末添加对应的 _recursiveLogin 调用。
593
+
594
+ 对于类方法: _recursiveLogin("ClassName", "method_name")
595
+ 对于普通函数: _recursiveLogin("", "function_name")
596
+ """
597
+ calls_to_add = []
598
+ deletions = []
599
+
600
+ # 1. 收集所有类定义的位置和缩进
601
+ class_pattern = re.compile(r'^(\s*)class\s+(\w+)', re.MULTILINE)
602
+ classes = [(m.start(), len(m.group(1)), m.group(2))
603
+ for m in class_pattern.finditer(content)]
604
+
605
+ # 2. 查找所有 @recursive 装饰器
606
+ decorator_pattern = re.compile(r'^\s*@\s*recursive\s*$\n?', re.MULTILINE)
607
+
608
+ for dec_match in decorator_pattern.finditer(content):
609
+ dec_end = dec_match.end()
610
+
611
+ # 查找接下来的函数定义(跳过可能的空行)
612
+ after_decorator = content[dec_end:]
613
+ func_match = re.search(r'^(\s*)def\s+([^\s\(]+)', after_decorator, re.MULTILINE)
614
+
615
+ if not func_match:
616
+ continue
617
+
618
+ func_indent_len = len(func_match.group(1))
619
+ func_name = func_match.group(2)
620
+
621
+ # 3. 确定类名:查找装饰器前最近的、缩进小于函数缩进的类
622
+ class_name = ""
623
+ for cls_pos, cls_indent_len, cls_name in reversed(classes):
624
+ if cls_pos < dec_match.start() and func_indent_len > cls_indent_len:
625
+ class_name = cls_name
626
+ break
627
+
628
+ # 4. 记录删除位置和调用信息
629
+ deletions.append((dec_match.start(), dec_end))
630
+ calls_to_add.append(f'_recursiveLogin("{class_name}", "{func_name}")')
631
+
632
+ # 5. 应用删除(倒序避免位置偏移)
633
+ if not deletions:
634
+ return content
635
+
636
+ result = content
637
+ for start, end in sorted(deletions, key=lambda x: x[0], reverse=True):
638
+ result = result[:start] + result[end:]
639
+
640
+ # 6. 在文末添加调用
641
+ if calls_to_add:
642
+ result = '\n'.join(calls_to_add) + '\n' + result
643
+
644
+ return result
645
+
646
+ @staticmethod
647
+ def process_mate_code(code):
648
+ # 用于存储匹配到的信息
649
+ mate_assignments = []
650
+ # 匹配变量赋值为Mate()的正则表达式,允许变量定义中包含或不包含类型注解
651
+ assign_pattern = re.compile(r'(\w+)\s*(?:\:\s*\w*)?\s*=\s*Mate\s*\(')
652
+ # 匹配类定义的正则表达式
653
+ class_pattern = re.compile(r'class\s+(\w+)')
654
+ # 用于记录当前所在的类名
655
+ current_class = None
656
+ # 将代码按行分割
657
+ lines = code.split('\n')
658
+ # 遍历每一行
659
+ for i, line in enumerate(lines):
660
+ # 匹配类定义
661
+ class_match = class_pattern.match(line)
662
+ if class_match:
663
+ current_class = class_match.group(1)
664
+ # 匹配变量赋值为Mate()
665
+ assign_match = assign_pattern.search(line)
666
+ if assign_match:
667
+ # 检查group(1)前面同一行内是否有#,如果有则忽略
668
+ comment = re.search(r'#', line[:assign_match.start()])
669
+ if comment:
670
+ continue
671
+ variable_name = assign_match.group(1)
672
+ # 存储匹配到的信息
673
+ mate_assignments += [(variable_name, current_class)]
674
+
675
+ output_strings = []
676
+ for variable_name, class_name in mate_assignments:
677
+ output_string = f"# > insert Object.defineProperty ({class_name}, '{variable_name}', property.call ({class_name}, {class_name}.{variable_name}._MateGet_, {class_name}.{variable_name}._MateSet_));"
678
+ output_strings.append(output_string)
679
+
680
+ return code + '\n'.join(output_strings)
681
+
682
+
683
+ @staticmethod
684
+ def remove_long_docstring(content:str) -> str:
685
+ """
686
+ 移除长注释 | remove long docstring
687
+ """
688
+ code = re.sub(r'"""[^"]*"""', '', content)
689
+ code = re.sub(r"'''[^']*'''", '', code)
690
+ return code
691
+
692
+
693
+ class CompilerBase(Compiler_Utils):
694
+
695
+ def __init__(self):
696
+ src_dir = "src"
697
+ build_dir = "build"
698
+ # check
699
+ if not os.path.exists(src_dir):
700
+ core.error('Compiler.__init__', core.lformat(LOC_FILE_NOT_EXISTS, ['src', src_dir]), head='\n', ln=config.language)
701
+
702
+ src_dir = os.path.abspath(src_dir)
703
+ build_dir = os.path.abspath(build_dir)
704
+ base_dir = os.path.dirname(src_dir)
705
+ lib_dir = os.path.join(base_dir, 'library')
706
+ built_dir = os.path.join(base_dir, 'builtin')
707
+
708
+ # 在builtin文件下搜索需要跳过的文件,计入到PYFILE_IGNORE_CHECK_FNAMES中
709
+ for fname in os.listdir(os.path.join(base_dir, "builtin")):
710
+ if fname.endswith('.py') and fname not in ['const.py', 'proto.py', 'utils.py']:
711
+ self.PYFILE_IGNORE_CHECK_FNAMES.append(f'builtin/{fname}')
712
+
713
+ self.src_dir = os.path.abspath(src_dir)
714
+ self.lib_dir = os.path.abspath(lib_dir)
715
+ self.build_dir = os.path.abspath(build_dir)
716
+ self.built_dir = os.path.abspath(built_dir)
717
+ self.target_dir = os.path.join(self.build_dir, '__target__')
718
+ self.build_name = os.path.basename(self.build_dir)
719
+
720
+ @property
721
+ def builtin_py(self) -> str:
722
+ """
723
+ 返回builtin目录下的__init__.py的路径 | return the path of __init__.py in builtin
724
+ """
725
+ return os.path.join(self.built_dir, '__init__.py')
726
+
727
+ @property
728
+ def target_py(self) -> str:
729
+ """
730
+ 返回build下的main.py的路径 | return the path of main.py in build
731
+ """
732
+ return os.path.join(self.build_dir, 'main.py')
733
+
734
+ @property
735
+ def target_js(self):
736
+ """
737
+ 返回build下的main.js的路径 | return the path of main.js in build
738
+ """
739
+ return os.path.join(self.target_dir, 'main.js')
740
+
741
+
742
+ class Compiler(CompilerBase):
743
+ def pre_compile(self):
744
+ """
745
+ 预编译 | Precompile
746
+ """
747
+ src_paths: list[str] = self.copy_to() # 复制src到build目录 | copy all files in src to build
748
+ # 获取src目录下的所有.py文件的路径 | get the paths of all .py files under src
749
+
750
+ core.lprint(WAIT, LOC_PREPROCESSING, end="", ln=config.language)
751
+ py_fpath, py_names, warn_flag = [], [], False
752
+ for root, dirs, files in os.walk(self.build_dir):
753
+ for file in files:
754
+ if file.endswith('.py'):
755
+ fpath: str = str(os.path.join(root, file))
756
+
757
+ # 将PYFILE_PRAGMA_INSERTS.replace("\t", "").replace(" ", "")插入到文件开头
758
+ content = self.auto_read(fpath)
759
+ content = self.PYFILE_PRAGMA_INSERTS.replace("\t", "").replace(" ", "") + content
760
+ # content = self.remove_long_docstring(content) # 移除长注释 | remove long docstring
761
+
762
+ with open(fpath, 'w', encoding='utf-8') as f: # 注意,这里修改的是build目录下的文件,不是源文件 | Note that the file under the build directory is modified here, not the source file
763
+ f.write(content)
764
+
765
+ # 得到src目录后面的内容
766
+ rel_name = os.path.relpath(fpath, self.build_dir).replace('\\', '/')
767
+ py_names.append(rel_name.replace('/', '.'))
768
+ py_fpath.append(fpath)
769
+ warn_flag |= self.potential_check(fpath, rel_name)
770
+ if warn_flag:
771
+ print() # 换行
772
+
773
+ _usubs_ = [] # update_subclass
774
+ _pre_import_, _pre_imp_detail_ = [], {} # > import
775
+ _imports = [] # chain import
776
+ _pre_sort_ = {} # > sort
777
+ _pre_define_ = {} # > define
778
+ _js_replace_, _insert_id_ = {}, 0 # > insert
779
+
780
+ # -------------------------------- ONLY IMPORT * -------------------------------- #
781
+ # 只允许from xxx import *的情况 | only allow from xxx import *
782
+ for i, fpath in enumerate(py_fpath):
783
+ content = self.auto_read(fpath)
784
+ for line in content.split('\n'):
785
+ # 1. 检查 import xxx的情况 | check import xxx
786
+ m = re.match(r'\s*import\s+([^\s]+)', line)
787
+ if m:
788
+ core.error('Compiler.pre_compile', core.lformat(LOC_IMPORT_STAR_ERROR, [m.group(1), m.group(1)]), head='\n', ln=config.language)
789
+ # 2. 检查 from xxx import yyys的情况(yyys不能是*) | check from xxx import yyys(yyys can't be *)
790
+ m = re.match(r'\n\s*from\s+([^\s]+)\s+import\s+([^\s]+)', line)
791
+ if m and (not m.group(2) or m.group(2)[0] != '*'):
792
+ core.error('Compiler.pre_compile', core.lformat(LOC_IMPORT_STAR2_ERROR, [m.group(1), m.group(2), m.group(1)]), head='\n', ln=config.language)
793
+
794
+ self.expand_folder_imports(fpath, self.build_dir)
795
+
796
+ # -------------------------------- EXPAND IMPORT * -------------------------------- #
797
+ _imports = self.find_chain_import(self.target_py, [os.path.dirname(self.src_dir), self.src_dir])
798
+ _js_imports = self.relist_pyimports_to_jsimports(self.build_dir, _imports)
799
+
800
+ # ----------------------------------- REMOVE ----------------------------------- #
801
+ # 移除所有# > remove所在行的内容
802
+ # | remove all # > remove in .py files
803
+ for fpath in py_fpath:
804
+ content = self.auto_read(fpath)
805
+ new_content = ""
806
+ for line in content.split('\n'):
807
+ if not re.search(r'#\s*>\s*remove', line):
808
+ new_content += line + '\n'
809
+
810
+ with open(fpath, 'w', encoding='utf-8') as f:
811
+ f.write(new_content)
812
+
813
+ # ------------------------------------ SORT ------------------------------------ #
814
+ # 获取所有.py文件中的所有# > sort的内容,并记录下来(不存在则默认为65535)
815
+ # | get all # > sort in .py files, and record them (default 65535 if not exists)
816
+ for i, fpath in enumerate(py_fpath):
817
+ fname = py_names[i]
818
+ if fname.endswith('__init__.py'):
819
+ fname = fname[:-12] + '.js'
820
+ else:
821
+ fname = fname[:-3] + '.js'
822
+ content = self.auto_read(fpath)
823
+ m = re.search(r'#\s*>\s*sort\s+(\d+)', content)
824
+ if m:
825
+ try:
826
+ sort_num = int(m.group(1))
827
+ except ValueError:
828
+ core.warn('Compiler.pre_compile', core.lformat(LOC_SORT_NUMBER_ERROR, [m.group(1)]), end='', head='\n', ln=config.language)
829
+ sort_num = 65535
830
+ _pre_sort_[fname] = sort_num
831
+ else:
832
+ _pre_sort_[fname] = 65535
833
+
834
+ # ------------------------------------ 自定义:调用process_mate_code ------------------------------------ #
835
+ for fpath in py_fpath:
836
+ content = self.auto_read(fpath)
837
+ content = self.process_mate_code(content) # 调用process_mate_code
838
+ with open(fpath, 'w', encoding='utf-8') as f:
839
+ f.write(content)
840
+
841
+ # ------------------------------------ DEFINE ------------------------------------ #
842
+ # 扫描所有# > define的内容,然后在.py中移除这些行,并记录下来
843
+ # | get all # > define in .py files, and record them
844
+ for fpath in py_fpath:
845
+ content = self.auto_read(fpath)
846
+ new_content = ""
847
+ for line in content.split('\n'):
848
+ # re.compile(r'#\s*define\s+([^\s]+)\s+([^\n]*)')
849
+ m = re.search(r'#\s*>\s*define\s+([^\s]+)\s+([^\n]*)', line)
850
+ if m:
851
+ _pre_define_[m.group(1)] = m.group(2)
852
+ new_content += '\n'
853
+ else:
854
+ new_content += line + '\n'
855
+
856
+ with open(fpath, 'w', encoding='utf-8') as f:
857
+ f.write(new_content)
858
+
859
+ # 按照keys的顺序,先用前面的key对应的内容去依次替换后面的key对应的value中
860
+ # | replace the value of the key with the content of the previous key in order
861
+ _def_keys = list(_pre_define_.keys())
862
+ _keys_len = len(_def_keys)
863
+ for i in range(_keys_len - 1):
864
+ for j in range(i + 1, _keys_len):
865
+ _pre_define_[_def_keys[j]] = _pre_define_[_def_keys[j]].replace(_def_keys[i], _pre_define_[_def_keys[i]])
866
+
867
+ # ------------------------------------ DEFINE:REPLACE ------------------------------------ #
868
+ # 将刚才记录的define替换到.py中(注意优先替换更长的串)(因此先排序)
869
+ # | replace the defined content to .py files (replace the longer string first)
870
+ _def_keys.sort(key=lambda x: len(x), reverse=True)
871
+ for fpath in py_fpath:
872
+ content = self.auto_read(fpath)
873
+
874
+ for key in _def_keys:
875
+ content = re.sub(r'[^_A-Za-z0-9]' + key, self._kfc_wrapper(_pre_define_[key]), content)
876
+
877
+ with open(fpath, 'w', encoding='utf-8') as f:
878
+ f.write(content)
879
+
880
+ # ------------------------------------ IF BLOCK ------------------------------------ #
881
+ # 预处理if块,将 # > if, # > elif, # > else, # > endif 替换为实际的程序内容
882
+ # | preprocess if block, replace # > if, # > elif, # > else, # > endif to actual code
883
+ for fpath in py_fpath:
884
+ content = self.auto_read(fpath)
885
+
886
+ content = self.preprocess_if_block(content, _pre_define_)
887
+
888
+ with open(fpath, 'w', encoding='utf-8') as f:
889
+ f.write(content)
890
+
891
+ # ------------------------------------ INSERT ------------------------------------ #
892
+ # 扫描所有# > insert的内容,然后在.py中将整行替换为# __pragma__("js", __JS_INSERT_{id})
893
+ # | get all # > insert in .py files, and replace the whole line with # __pragma__("js", __JS_INSERT_{id})
894
+ for fpath in py_fpath:
895
+ content = self.auto_read(fpath)
896
+ new_content = ""
897
+ for line in content.split('\n'):
898
+ # re.compile(r'#\s*insert\s*([^\n]*)')
899
+ # '# > insert if(obj && obj.body) for(var p of obj.body) if (p.type == MOVE) return true;'
900
+ m = re.search(r'#\s*>\s*insert\s+([^\n]*)', line)
901
+ if m:
902
+ _sign_index_ = line.find('#') # 必然存在
903
+ _js_key_ = f"__JS_INSERT_{_insert_id_:08d}"
904
+ _js_replace_[_js_key_] = m.group(1)
905
+
906
+ new_content += line[:_sign_index_] + f'# __pragma__("js", "{_js_key_}")\n'
907
+ _insert_id_ += 1
908
+ else:
909
+ new_content += line + '\n'
910
+
911
+ with open(fpath, 'w', encoding='utf-8') as f:
912
+ f.write(new_content)
913
+
914
+ # ------------------------------------ 自定义:调用stage_recursive_replace ------------------------------------ #
915
+ for fpath in py_fpath:
916
+ content = self.auto_read(fpath)
917
+ content = self.stage_recursive_replace(content) # 调用stage_recursive_replace
918
+ with open(fpath, 'w', encoding='utf-8') as f:
919
+ f.write(content)
920
+
921
+
922
+ core.lprint(GREEN.format('[2/6]'), LOC_DONE, " ", LOC_PREPROCESSING_FINISH, sep="", head="\r", ln=config.language)
923
+ return _imports, _js_imports, _pre_sort_, _pre_define_, _js_replace_
924
+
925
+ def transcrypt_cmd(self):
926
+ # 执行cmd命令: transcrypt -b -m -n -s -e 6 target | execute cmd: transcrypt -b -m -n -s -e 6 target
927
+ # 并获取cmd得到的输出 | and get the output of the cmd
928
+ cmd = 'transcrypt -b -m -n -s -e 6 %s' % self.target_py
929
+ core.lprint(WAIT, core.lformat(LOC_TRANSCRYPTING, [cmd]), end="", ln=config.language)
930
+ p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
931
+ stdout, stderr = p.communicate()
932
+ if 'Error while compiling' in stdout.decode():
933
+ print('\r' + stdout.decode())
934
+ core.error('Compiler.transcrypt_cmd', LOC_TRANSCRYPTING_ERROR, indent=1, head='\n', ln=config.language)
935
+ core.lprint(GREEN.format('[3/6]'), LOC_DONE, " ", LOC_TRANSCRYPTING_FINISH, sep="", head="\r", ln=config.language)
936
+
937
+ @staticmethod
938
+ def _keep_lbracket(matched) -> str:
939
+ """
940
+ 如果第一个字符是{, 则返回'{',否则返回'' | if the first char is {, return '{', else return ''
941
+ :param matched:
942
+ :return:
943
+ """
944
+ return '{' if matched.group(0)[0] == '{' else ''
945
+
946
+ @staticmethod
947
+ def _keep_first_char(matched: re.Match) -> str:
948
+ """
949
+ 保留第一个字符 | keep the first char
950
+ :param matched: re.match object | re.match对象
951
+ :return:
952
+ """
953
+ return matched.group(0)[0]
954
+
955
+ @staticmethod
956
+ def _kfc_wrapper(replace: str) -> callable:
957
+ """
958
+ 获取一个保留第一个字符的函数 | get a function to keep the first char
959
+ :param replace: str
960
+ :return: function
961
+ """
962
+
963
+ def _kfc(matched) -> str:
964
+ return matched.group(0)[0] + replace
965
+
966
+ return _kfc
967
+
968
+ def analyze_rebuild_main_js(self, defs: dict[str, object], modules=None) -> tuple[str, list[str]]:
969
+ """
970
+ 分析main.js中导入的模块名称和先后顺序, 并重新生成main.js | analyze the module names and order imported in main.js, and rebuild main.js
971
+ * 主要移除非SYSTEM_MODULES_IGNORE中的模块导入语句 | mainly remove the module import statements that are not in SYSTEM_MODULES_IGNORE
972
+ :param defs: dict{define: value} 定义的变量 | defined variables
973
+ :return: imports : str, modules (names: str)
974
+ imports是一段用于放在js主体开头的import语句 | imports is a string of import statements to be placed at the beginning of the js body
975
+ modules是一个list,包含了所有的模块名称 | modules is a list containing all module names
976
+ 其中的内容可能是这样的: ['./game.utils.js', './game.proto.js', './game.const.js', ...]
977
+ """
978
+
979
+ # create undefined
980
+ imports = ""
981
+
982
+ # if defs.get('USE_TUTORIAL_FLAG', '0') == '0' and defs.get('USE_ARENA_FLAG', '0') == '0':
983
+ # imports += 'var Flag = undefined;\n'
984
+ # if defs.get('USE_SCORE_COLLECTOR', '0') == '0':
985
+ # imports += 'var ScoreController = undefined;\nvar RESOURCE_SCORE = undefined;\n'
986
+ # imports += '\n'
987
+
988
+ core.lprint(WAIT, LOC_ANALYZING_AND_REBUILDING_MAIN_JS, end="", ln=config.language)
989
+
990
+ content = self.auto_read(self.target_js)
991
+ if modules is None: modules = []
992
+ new_modules, new_content = [],""
993
+ for line in content.split('\n'):
994
+ m = re.search(self.JS_IMPORT_PAT, line)
995
+ if not m:
996
+ new_content += line + '\n'
997
+ continue
998
+ # remove ignore if in SYSTEM_MODULES_IGNORE
999
+ module = m.group(1)
1000
+
1001
+ _ignore = False
1002
+ if module in modules: _ignore = True
1003
+ if module in new_modules: _ignore = True
1004
+ if not _ignore: new_modules.append(module)
1005
+
1006
+ # conbine modules
1007
+ modules = new_modules + modules
1008
+ new_modules = []
1009
+ for module in modules:
1010
+ _ignore = False
1011
+ if not _ignore and module.startswith(self.OTHER_IGNORE_WITH): _ignore = True
1012
+ for keeps in self.BUILTIN_TRANS:
1013
+ if module.endswith(keeps): _ignore = False
1014
+ if not _ignore: new_modules.append(module)
1015
+ modules = new_modules
1016
+
1017
+ # save raw main.js
1018
+ with open(self.target_js[:-3] + ".raw.js", 'w', encoding='utf-8') as f:
1019
+ f.write(content)
1020
+
1021
+ # write rebuild main.js
1022
+ with open(self.target_js, 'w', encoding='utf-8') as f:
1023
+ f.write(new_content)
1024
+
1025
+ core.lprint(GREEN.format('[4/6]'), LOC_DONE, " ", LOC_ANALYZING_AND_REBUILDING_MAIN_JS_FINISH, sep="", head="\r", ln=config.language)
1026
+
1027
+ return imports, modules
1028
+
1029
+ @staticmethod
1030
+ def remove_js_import(raw) -> str:
1031
+ """
1032
+ 移除js中的import行
1033
+ :param raw:
1034
+ :return:
1035
+ """
1036
+ return re.sub(r'import[^\n]*\n', '', raw)
1037
+
1038
+ def generate_total_js(self, usr_modules, t_imps: list[str], f_sorts, f_replaces, g_replaces) -> str:
1039
+ """
1040
+ 生成总的main.js
1041
+ 按照如下顺序组合:
1042
+ ./org.transcrypt.__runtime__.js
1043
+ ./game.const.js # IGNORE
1044
+ ./game.proto.js # IGNORE
1045
+ ./game.utils.js # IGNORE
1046
+ {usr_modules}
1047
+ :param usr_modules: list[str] # js vm + 用户自定义模块
1048
+ :param t_imps: list[str] # main前需要导入的模块
1049
+ :param f_sorts: dict{module_name: sort_priority}
1050
+ :param f_replaces: dict{module_name: dict{old: new}}
1051
+ :param g_replaces: dict{old: new}
1052
+ :return: str
1053
+ """
1054
+ arena_name = const.ARENA_NAMES.get(config.arena, const.ARENA_NAMES['green']) # like green -> spawn_and_swamp
1055
+ self.TOTAL_INSERT_AT_HEAD += self.ARENA_IMPORTS_GETTER[arena_name]() # add arena imports
1056
+ total_js = f"const __VERSION__ = '{const.VERSION}';\nconst __PYTHON_VERSION__ = '{python_version_info}';" + self.TOTAL_INSERT_AT_HEAD + f"\nexport var LANGUAGE = '{config.language}';\n"
1057
+ total_js += f"const __AUTHOR__ = '{const.AUTHOR}';\nconst __AUTHOR_CN__ = '{const.BILIBILI_NAME}';"
1058
+
1059
+ core.lprint(WAIT, LOC_GENERATING_TOTAL_MAIN_JS, end="", ln=config.language)
1060
+
1061
+ # TODO: IMPS donot work
1062
+
1063
+ # resort modules
1064
+ f_sorts[self.JS_VM] = -1
1065
+
1066
+ for i in range(len(usr_modules)):
1067
+ for j in range(i + 1, len(usr_modules)):
1068
+ if f_sorts[usr_modules[i][2:]] > f_sorts[usr_modules[j][2:]]:
1069
+ usr_modules[i], usr_modules[j] = usr_modules[j], usr_modules[i]
1070
+
1071
+ # write modules
1072
+ for module in usr_modules:
1073
+ content = self.auto_read(os.path.join(self.target_dir, module))
1074
+ content = self.remove_js_import(content)
1075
+ for old, new in f_replaces.get(module, {}).items():
1076
+ content = re.sub(old, new, content)
1077
+ for old, new in self.TRANSCRYPT_ERROR_REPLACE.items():
1078
+ content = re.sub(old, new, content)
1079
+ total_js += f"\n// ---------------------------------------- Module:{module} "
1080
+ total_js += "----------------------------------------\n\n"
1081
+ total_js += content + '\n'
1082
+
1083
+ total_js += self.TOTAL_INSERT_BEFORE_MAIN
1084
+
1085
+ # write main.js
1086
+ content = self.auto_read(self.target_js)
1087
+ for old, new in self.TRANSCRYPT_ERROR_REPLACE.items():
1088
+ content = re.sub(old, new, content)
1089
+ total_js += content
1090
+
1091
+ # TOTAL_APPEND_ATEND
1092
+ total_js += self.TOTAL_APPEND_ATEND
1093
+
1094
+ # replace export-pat
1095
+ total_js = re.sub(self.JS_EXPORT_PAT, "", total_js)
1096
+
1097
+ # global replace
1098
+ for old, new in g_replaces.items():
1099
+ total_js = re.sub(old, new, total_js)
1100
+
1101
+ core.lprint(GREEN.format('[5/6]'), LOC_DONE, " ", LOC_GENERATING_TOTAL_MAIN_JS_FINISH, sep="", head="\r", ln=config.language)
1102
+
1103
+ # REPACE
1104
+ for old, new in self.TOTAL_SIMPLE_REPLACE_WITH.items():
1105
+ total_js = total_js.replace(old, new)
1106
+
1107
+ return total_js
1108
+
1109
+ def __parse_js_file_sort(self, fpath):
1110
+ """
1111
+ 解析js文件中的sort
1112
+ :param fpath:
1113
+ :return:
1114
+ """
1115
+ content = self.auto_read(fpath)
1116
+ m = re.search(r'//\s*>\s*sort\s+(\d+)', content)
1117
+ if m:
1118
+ return int(m.group(1))
1119
+ return 65535
1120
+
1121
+ def find_add_pure_js_files(self, sorts, modules):
1122
+ """
1123
+ 找到所有的纯js文件,并添加到modules中
1124
+ :param sorts:
1125
+ :param modules:
1126
+ :return:
1127
+ """
1128
+ for root, dirs, files in os.walk(self.lib_dir):
1129
+ for file in files:
1130
+ if file.endswith('.js') and file not in modules:
1131
+ fpath = str(os.path.join(root, file))
1132
+ fname = file.replace('\\', '/')
1133
+ # copy file to target
1134
+ shutil.copy(fpath, os.path.join(self.target_dir, fname))
1135
+ sorts[fname] = self.__parse_js_file_sort(fpath)
1136
+ modules.append("./" + fname)
1137
+
1138
+ def compile(self, paste=False):
1139
+ """
1140
+ 编译
1141
+ :param paste: 是否复制到剪贴板
1142
+ :return:
1143
+ """
1144
+ imps, jimps, sorts, defs, reps = self.pre_compile()
1145
+ self.transcrypt_cmd()
1146
+ imports, modules = self.analyze_rebuild_main_js(defs, jimps)
1147
+ self.find_add_pure_js_files(sorts, modules)
1148
+ total_js = imports + "\n" + self.generate_total_js(replace_src_prefix(modules), imps, sorts, self.FILE_STRONG_REPLACE, reps)
1149
+
1150
+ core.lprint(WAIT, LOC_EXPORTING_TOTAL_MAIN_JS, end="", ln=config.language)
1151
+
1152
+ # ensure exported main.mjs path
1153
+ build_main_mjs = os.path.join(self.build_dir, 'main.mjs')
1154
+
1155
+ mjs_path = config.target if config.target is not None else config.TARGET_GETTER()
1156
+ if not mjs_path.endswith('js'):
1157
+ mjs_path = os.path.join(mjs_path, 'main.mjs')
1158
+
1159
+ # write main.mjs
1160
+ with open(build_main_mjs, 'w', encoding='utf-8') as f:
1161
+ f.write(total_js)
1162
+
1163
+ # export main.mjs
1164
+ dir_path = os.path.dirname(mjs_path)
1165
+ if not os.path.exists(dir_path):
1166
+ core.error('Compiler.compile', core.lformat(LOC_EXPORT_DIR_PATH_NOT_EXISTS, [dir_path]), head='\n', ln=config.language)
1167
+ with open(mjs_path, 'w', encoding='utf-8') as f:
1168
+ f.write(total_js)
1169
+
1170
+ core.lprint(GREEN.format('[6/6]'), LOC_DONE, " ", LOC_EXPORTING_TOTAL_MAIN_JS_FINISH, sep="", head="\r", ln=config.language)
1171
+
1172
+ if mjs_path != build_main_mjs:
1173
+ core.lprint(Fore.LIGHTBLUE_EX + '[Info] ' + Fore.RESET, core.lformat(LOC_USR_EXPORT_INFO, [mjs_path]), ln=config.language)
1174
+
1175
+ # copy to clipboard
1176
+ if paste:
1177
+ pyperclip.copy(total_js)
1178
+ core.lprint(LOC_DONE, " ", LOC_COPY_TO_CLIPBOARD, ln=config.language)
1179
+
1180
+ def clean(self):
1181
+ """
1182
+ 清除build目录下除了main.mjs之外的所有文件和目录
1183
+ * 先复制main.mjs到src目录下,然后删除build目录,再将main.mjs剪切回build目录
1184
+ :return:
1185
+ """
1186
+ core.lprint(WAIT, LOC_CLEAN_BUILD_DIR, end="", ln=config.language)
1187
+ if not os.path.exists(self.build_dir):
1188
+ core.error('Compiler.clean', LOC_BUILD_DIR_NOT_EXISTS, indent=1, head='\n', ln=config.language)
1189
+
1190
+ if not os.path.exists(os.path.join(self.build_dir, 'main.mjs')):
1191
+ core.error('Compiler.clean', LOC_MAIN_MJS_NOT_EXISTS, indent=1, head='\n', ln=config.language)
1192
+
1193
+ # copy main.mjs to src
1194
+ shutil.copy(os.path.join(self.build_dir, 'main.mjs'), os.path.join(self.src_dir, 'main.mjs'))
1195
+
1196
+ # remove build dir
1197
+ shutil.rmtree(self.build_dir)
1198
+
1199
+ # create build dir
1200
+ os.makedirs(self.build_dir)
1201
+
1202
+ # move main.mjs to build dir
1203
+ shutil.move(os.path.join(self.src_dir, 'main.mjs'), os.path.join(self.build_dir, 'main.mjs'))
1204
+
1205
+ core.lprint(GREEN.format('[Done]'), LOC_CLEAN_BUILD_DIR_FINISH, head="\r", ln=config.language)
1206
+
1207
+ def clear(self):
1208
+ """
1209
+ 清除build目录下所有文件和目录
1210
+ :return:
1211
+ """
1212
+ core.lprint(WAIT, LOC_CLEAN_BUILD_DIR, end="", ln=config.language)
1213
+ if not os.path.exists(self.build_dir):
1214
+ core.lprint(LOC_BUILD_DIR_NOT_EXISTS, ln=config.language)
1215
+
1216
+ shutil.rmtree(self.build_dir)
1217
+ os.makedirs(self.build_dir)
1218
+
1219
+ core.lprint(GREEN.format('[Done]'), LOC_CLEAN_BUILD_DIR_FINISH, head="\r", ln=config.language)
1220
+
1221
+
1222
+ if __name__ == '__main__':
1223
+ compiler = Compiler('src', 'library', 'build')
1224
+ compiler.compile()
1225
+ compiler.clean()