-
Notifications
You must be signed in to change notification settings - Fork 1
/
Parser.py
2964 lines (2787 loc) · 223 KB
/
Parser.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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import ast
import copy
import json
import os
import re
from typing import Callable
import system.mc as mc
from config import custom_functions # 自定义 函数调用表
from config import defualt_DataPath # 项目Data文件路径
from config import defualt_NAME # 项目名称
from config import defualt_PATH # 默认路径
from config import defualt_STORAGE # STORAGE
from config import scoreboard_objective # 默认记分板
from config import system_functions # 内置 函数调用表
from model.mc_nbt import IntArray, MCNbt, MCStorage, RawJsonText
# from model.mcf_modifier import mcf_modifier
# from model.file_ops import editor_file
from model.py_modifier import py_modifier
from model.DebuggerOut import DebuggerOut
from model.DebuggerOut import Logger
from model.uuid_generator import get_uuid, uuid_to_list
from read_config import read_json
scoreboard_objective2 = scoreboard_objective+'2'
#更新配置
def update_config_call(function):
def wrapper(*args,**kwargs):
update_config()
return function(*args,**kwargs)
return wrapper
def update_config():
from TMCFM import Pathtime
cfg = read_json.read('config.json')['config']
global defualt_DataPath
global defualt_PATH
defualt_DataPath = cfg['path'][Pathtime]+"data/"
defualt_PATH = cfg['path'][Pathtime]+"data/"+cfg['name'] + '/'
class Parser(py_modifier):
'''解析程序'''
@update_config_call
def __init__(self,content,*args,**kwargs) -> None:
self.code = content
# 模拟栈 [{ "data":[{"id":"x","value":"","is_global":False},{...}],"is_end":0,"is_return":0,"is_break":0,"is_continue":0,"return":[{"id":"x","value":""}],"type":"" },"exp_operation":[{"value":""}],"functions":[{"id":"","args":[],"call":"","BoolOpTime":0,"Subscript":[{"value":""}]}]]
# data为记录数据,is_return控制当前函数是否返回,is_end控制该函数是否终止,is_break控制循环是否终止,is_continue是否跳过后续的指令,return 记录调用的函数的返回值 , exp_operation 表达式运算的过程值(栈) is_global 判断该变量是否为全局变量 functions记录函数参数列表,函数调用接口,当前函数 BoolOpTime 条件判断 累计次数 Subscript为记录切片结果 condition_time记录该函数逻辑运算时深度遍历的编号(属于临时变量) "boolOPS"记录逻辑运算的结果 elif_time 记录 elif次数(临时数据) while_time记录 while次数 for_time 记录 for 次数 for_list 记录for迭代的列表([{"value":xx},{..},...]) "call_list" 调用函数的参数列表( [{"value":"","id":"",is_constant:True} ] ,若有id则为kwarg ) , class_list 记录 自定义类的函数与数据 "record_condition" 统计逻辑次数
# 类型: BinOp Constant Name BoolOp Compare UnaryOp Subscript list tuple Call Attribute
self.stack_frame:list[dict] = []
self.py_append_tree()
#初始化计分板
self.write_file('',f'scoreboard objectives add {scoreboard_objective} dummy\n',f2="_init",**kwargs)
# self.write_file('',f'scoreboard objectives remove {scoreboard_objective2} dummy\n',f2="_init",**kwargs)
self.write_file('',f'scoreboard objectives add {scoreboard_objective2} dummy\n',f2="_init",**kwargs)
self.write_file('',f'scoreboard players reset * {scoreboard_objective2}\n',f2="_init",**kwargs)
self.write_file('',f'#初始化栈\n',f2="_init",**kwargs)
self.write_file('',f'execute unless score #{defualt_STORAGE}.stack.end {scoreboard_objective} matches 1 run data modify storage {defualt_STORAGE} stack_frame set value [{{"data":[],"return":[],"boolOPS":[],"boolResult":[],"for_list":[],"dync":{{}}}}]\n',f2="_init",**kwargs)
self.write_file('',f'execute unless score #{defualt_STORAGE}.stack.end {scoreboard_objective} matches 1 run data modify storage {defualt_STORAGE} data set value {{"exp_operation":[],"list_handler":[],"dict_handler":[],"call_list":[],"Subscript":""}}\n',f2="_init",**kwargs)
self.write_file('',f'#初始化堆\n',f2="_init",**kwargs)
self.write_file('',f'execute unless score #{defualt_STORAGE}.stack.end {scoreboard_objective} matches 1 run data modify storage {defualt_STORAGE} heap set value []\n',f2="_init",**kwargs)
self.mcf_call_function(f'_init','__main__',False,f'',**kwargs)
self.write_file('__main__',f'\n',**kwargs)
self.parse('__main__',**kwargs)
def parse(self,func:str,*args,**kwargs):
'''func为当前函数的名称'''
code = copy.deepcopy(self.code)
code_ = ast.parse(code)
#遍历python的ast树
self.walk(code_.body,func,-1,**kwargs)
print(self.stack_frame)
def walk(self,tree:list,func:str,index:-1,*args,**kwargs):
'''遍历AST'''
kwargs_ = copy.deepcopy(kwargs)
for item in tree:
# 赋值
if isinstance(item,ast.Assign):
Logger(func,'赋值 '+ast.unparse(item),**kwargs)
self.Assign(item,func,index,**kwargs)
# 赋值
if isinstance(item,ast.AnnAssign):
Logger(func,'注解赋值 '+ast.unparse(item),**kwargs)
self.AnnAssign(item,func,index,**kwargs)
# 全局化
elif isinstance(item,ast.Global):
self.Global(item,func,index,**kwargs)
# 增强分配+= -= *= /=
elif isinstance(item,ast.AugAssign):
Logger(func,'增强赋值 '+ast.unparse(item),**kwargs)
self.AugAssign(item,func,index,**kwargs)
# 函数定义
elif isinstance(item,ast.FunctionDef):
Logger(func,f'函数定义 (NAME: {item.name})',**kwargs)
self.FunctionDef(item,item.name,index,func,**kwargs)
# 类定义
elif isinstance(item,ast.ClassDef):
Logger(func,f'类定义 (NAME: {item.name})'+item.name,**kwargs)
self.ClassDef(item,item.name,index,**kwargs)
# 函数调用
elif isinstance(item,ast.Expr):
Logger(func,f'表达式调用 (CALL: {ast.unparse(item)})',**kwargs)
self.Expr(item,func,index,**kwargs)
# 函数返回
elif isinstance(item,ast.Return):
Logger(func,f'函数返回 (RETURN: {ast.unparse(item)})',**kwargs)
self.stack_frame[-1]['Is_code_have_end'] = True
self.Return(item,func,**kwargs)
# 逻辑运算
elif isinstance(item,ast.If):
Logger(func,'If Start:'+ast.unparse(item.test),**kwargs)
self.stack_frame[-1]['condition_time'] = 0
self.stack_frame[-1]['elif_time'] = 0
self.stack_frame[-1]['BoolOpTime'] += 1
self.write_file(func,f'scoreboard players set #{defualt_NAME}.sys.c.{(self.stack_frame[-1]["BoolOpTime"])}.pass {scoreboard_objective} 0\n',**kwargs)
self.write_file(func,f'scoreboard players set #{defualt_NAME}.sys.c.{(self.stack_frame[-1]["BoolOpTime"])}.end {scoreboard_objective} 0\n',**kwargs)
self.If(item,self.stack_frame[-1]['condition_time'],func,True,**kwargs)
Logger(func,'If End',**kwargs)
# while 循环
elif isinstance(item,ast.While):
Logger(func,'While Start:'+ast.unparse(item.test),**kwargs)
self.stack_frame[-1]["In_loop"] = True
self.stack_frame[-1]['BoolOpTime'] += 1
self.While(item,func,**kwargs)
self.stack_frame[-1]["In_loop"] = False
Logger(func,'While End',**kwargs)
# For 循环
elif isinstance(item,ast.For):
Logger(func,'For Start:'+ast.unparse(item.target)+' in '+ast.unparse(item.iter),**kwargs)
self.stack_frame[-1]["In_loop"] = True
self.stack_frame[-1]['BoolOpTime'] += 1
self.For(item,func,**kwargs)
self.stack_frame[-1]["In_loop"] = False
Logger(func,'For End',**kwargs)
# Break
elif isinstance(item,ast.Break):
self.Break(item,func,**kwargs)
# Continue
elif isinstance(item,ast.Continue):
self.Continue(item,func,**kwargs)
kwargs = kwargs_
## 工具方法
# 动态命令
def build_dynamic_command(self,commands,func,**kwargs):
##处理参数
self.mcf_modify_value_by_value(f'storage {defualt_STORAGE} data.call_list','append',[],func,**kwargs)
for i in range(len(commands)):
self.Expr_set_value(ast.Assign(targets=[ast.Name(id=None)],value=commands[i]),func,**kwargs)
# self.mcf_modify_value_by_value(f'storage {defualt_STORAGE} stack_frame[-1].dync','set',{},func,**kwargs)
for i in range(len(commands)):
self.mcf_modify_value_by_from(f'storage {defualt_STORAGE} stack_frame[-1].dync.arg{i}','set',f'storage {defualt_STORAGE} data.call_list[-1][{i}].value',func,**kwargs)
self.mcf_call_function(f'{func}/dync_{self.stack_frame[0]["dync"]}/_start with storage {defualt_STORAGE} stack_frame[-1].dync',func,False,f'execute unless score #{defualt_STORAGE}.stack.end {scoreboard_objective} matches 1 run ',**kwargs)
# self.mcf_modify_value_by_value(f'storage {defualt_STORAGE} stack_frame[-1].dync','set',{},func,**kwargs)
self.write_file(func,f'data remove storage {defualt_STORAGE} data.call_list[-1]\n',**kwargs)
# 内容
kwargs['p'] = f'{func}/dync_{self.stack_frame[0]["dync"]}/'
kwargs['f2'] = f'_start'
self.write_file(func,f'## 动态命令\n$',inNewFile=True,**kwargs)
for i in range(len(commands)):
self.write_file(func,f'$(arg{i})',inNewFile=True,**kwargs)
self.stack_frame[0]["dync"] += 1
# 字符串列表转化为动态命令格式
def list_to_dynamic_command(self,arr,func,**kwargs)->list:
res = []
for i in arr:
res.append(ast.Constant(value=i, kind=None))
return res
# mcf动态命令构建
def mcf_build_dynamic_command(self,inputArgs,runFunction,func,**kwargs):
'''构造mcf版动态命令
- inputArgs 为传参列表([storage1,storage2等])
- runFunction 动态命令列表
'''
#动态命令
self.write_file(func,f' ##动态命令调用\n',**kwargs)
for i in range(len(inputArgs)):
self.mcf_modify_value_by_from(f'storage {defualt_STORAGE} stack_frame[-1].dync.arg{i}','set',inputArgs[i],func,**kwargs)
self.mcf_call_function(f'{func}/dync_{self.stack_frame[0]["dync"]}/_start with storage {defualt_STORAGE} stack_frame[-1].dync',func,False,f'execute unless score #{defualt_STORAGE}.stack.end {scoreboard_objective} matches 1 run ',**kwargs)
self.write_file(func,f' ##动态命令调用end\n',**kwargs)
# 内容
kwargs['p'] = f'{func}/dync_{self.stack_frame[0]["dync"]}/'
kwargs['f2'] = f'_start'
self.write_file(func,f'## 动态命令\n',inNewFile=True,**kwargs)
#
for i in runFunction:
self.write_file(func,i+'\n',inNewFile=True,**kwargs)
self.stack_frame[0]["dync"] += 1
##
## 赋值
# 赋值
def Assign(self,tree:ast.Assign,func:str,index:-1,*args,**kwargs):
'''赋值操作'''
# 类型扩建TODO
if isinstance(tree.value,ast.BinOp):
value = self.preBinOp(tree.value,tree.value.op,func,index,index,**kwargs)
for i in tree.targets:
if isinstance(i,ast.Name):
self.py_change_value(i.id,value["value"],False,func,False,index,**kwargs)
self.py_change_value_type(i.id,value["type"],index,False,True,func,**kwargs)
self.write_file(func,f'execute unless score #{defualt_STORAGE}.stack.end {scoreboard_objective} matches 1 run data modify storage {defualt_STORAGE} stack_frame[{index}].data[{{"id":"{i.id}"}}].value set {value["data"]}\n',**kwargs)
elif isinstance(i,ast.Attribute):
ClassC = ClassCall(self.stack_frame,**kwargs)
StoragePath = ClassC.class_var_to_str(i,func,**kwargs)
self.mcf_modify_value_by_from(f'{StoragePath}','set',value["data"],func,**kwargs)
ClassC.modify_class_var(i,func,tree.value,**kwargs)
elif isinstance(i,ast.Subscript):
x = []
def change(storage):
storage["value"] = value["value"]
storage["type"] = value["type"]
return storage
def change2(storage,func,**kwargs):
self.write_file(func,f'data modify {storage}.value set {value["data"]}\n',**kwargs)
self.write_file(func,f'data modify {storage}.type set {value["type"]}\n',**kwargs)
x.append(change2)
x.append(change)
returnValue = self.preSubscript(i,func,True,x,**kwargs)
if not value["isConstant"]: self.mcf_remove_Last_exp_operation(func,**kwargs)
elif isinstance(tree.value,ast.Constant):
# 常数赋值
for i in tree.targets:
if isinstance(i,ast.Name):
self.py_change_value(i.id,tree.value.value,True,func,False,index,**kwargs)
self.py_change_value_type(i.id,tree.value.value,index,True,True,func,**kwargs)
elif isinstance(i,ast.Attribute):
ClassC = ClassCall(self.stack_frame,**kwargs)
StoragePath = ClassC.class_var_to_str(i,func,**kwargs)
self.mcf_modify_value_by_value(f'{StoragePath}','set',tree.value.value,func,**kwargs)
ClassC.modify_class_var(i,func,tree.value.value,**kwargs)
ClassC.get_class_var(i,func,**kwargs)['value'] = tree.value.value
elif isinstance(i,ast.Subscript):
x = []
def change(storage):
storage["value"] = tree.value.value
storage["type"] = self.check_type(tree.value.value)
return storage
x.append(
lambda storage,func,**kwargs:self.mcf_modify_value_by_value(storage,'set',{"value":tree.value.value,"type":self.check_type(tree.value.value)},func,**kwargs)
)
x.append(change)
returnValue = self.preSubscript(i,func,True,x,**kwargs)
elif isinstance(tree.value,ast.Name):
# 变量赋值
for i in tree.targets:
if isinstance(i,ast.Name):
self.py_change_value2(i.id,tree.value.id,func,False,index,**kwargs)
self.py_change_value_type(i.id,self.py_get_type(tree.value.id,index),index,False,True,func,**kwargs)
elif isinstance(i,ast.Attribute):
ClassC = ClassCall(self.stack_frame,**kwargs)
StoragePath = ClassC.class_var_to_str(i,func,**kwargs)
self.mcf_modify_value_by_from(f'{StoragePath}','set',f'storage {defualt_STORAGE} stack_frame[{index}].data[{{"id":"{tree.value.id}"}}].value',func,**kwargs)
ClassC.modify_class_var(i,func,self.py_get_value(tree.value.id,func,**kwargs),**kwargs)
elif isinstance(i,ast.Subscript):
value = self.py_get_var_info(tree.value.id,self.stack_frame[-1]["data"])
x = []
def change(storage):
storage["value"] = value["value"]
storage["type"] = value["type"]
return storage
def change2(storage,func,**kwargs):
self.write_file(func,f'data modify {storage} set from storage {defualt_STORAGE} stack_frame[{index}].data[{{"id":"{tree.value.id}"}}]\n',**kwargs)
x.append(change2)
x.append(change)
returnValue = self.preSubscript(i,func,True,x,**kwargs)
elif isinstance(tree.value,ast.Subscript):
# 切片赋值
value = 0
returnValue = self.preSubscript(tree.value,func,**kwargs)
storage = returnValue["storage"]
value = returnValue["value"]
valueType = returnValue["type"]
for i in tree.targets:
if isinstance(i,ast.Name):
self.py_change_value(i.id,value,False,func,False,index,**kwargs)
self.py_change_value_type(i.id,valueType,index,False,True,func,**kwargs)
is_global = self.py_get_value_global(i.id,func,index,**kwargs)
if(is_global):
self.write_file(func,f'execute unless score #{defualt_STORAGE}.stack.end {scoreboard_objective} matches 1 run data modify storage {defualt_STORAGE} stack_frame[0].data[{{"id":"{i.id}"}}].value set from {storage}\n',**kwargs)
self.write_file(func,f'execute unless score #{defualt_STORAGE}.stack.end {scoreboard_objective} matches 1 run data modify storage {defualt_STORAGE} stack_frame[-1].data[{{"id":"{i.id}"}}].value set from {storage}\n',**kwargs)
elif isinstance(i,ast.Attribute):
ClassC = ClassCall(self.stack_frame,**kwargs)
StoragePath = ClassC.class_var_to_str(i,func,**kwargs)
self.mcf_modify_value_by_from(f'{StoragePath}','set',f'{storage}',func,**kwargs)
ClassC.modify_class_var(i,func,value,**kwargs)
elif isinstance(i,ast.Subscript):
x = []
def change(storage):
storage["value"] = returnValue["value"]
storage["type"] = returnValue["type"]
return storage
def change2(storage2,func,**kwargs):
self.write_file(func,f'data modify {storage2}.value set from {storage}\n',**kwargs)
x.append(change2)
x.append(change)
returnValue = self.preSubscript(i,func,True,x,**kwargs)
elif isinstance(tree.value,ast.Call):
# 函数返回值 赋值
value = self.Expr(ast.Expr(value=tree.value),func,-1,**kwargs)
# python 赋值 主要是查是否为全局变量
for i in tree.targets:
if isinstance(i,ast.Name):
self.py_change_value(i.id,value['value'],False,func,False,index,**kwargs)
self.py_change_value_type(i.id,value['type'],index,False,True,func,**kwargs)
is_global = self.py_get_value_global(i.id,func,index,**kwargs)
# mcf 赋值
if is_global:
self.mcf_modify_value_by_from(f'storage {defualt_STORAGE} stack_frame[0].data[{{"id":"{i.id}"}}].value','set',f'storage {defualt_STORAGE} stack_frame[-1].return[-1].value',func,**kwargs)
self.mcf_modify_value_by_from(f'storage {defualt_STORAGE} stack_frame[-1].data[{{"id":"{i.id}"}}].value','set',f'storage {defualt_STORAGE} stack_frame[-1].return[-1].value',func,**kwargs)
elif isinstance(i,ast.Attribute):
ClassC = ClassCall(self.stack_frame,**kwargs)
StoragePath = ClassC.class_var_to_str(i,func,**kwargs)
self.mcf_modify_value_by_from(f'{StoragePath}','set',f'storage {defualt_STORAGE} stack_frame[-1].return[-1].value',func,**kwargs)
ClassC.modify_class_var(i,func,value,**kwargs)
elif isinstance(i,ast.Subscript):
x = []
def change(storage):
storage["value"] = value["value"]
storage["type"] = value["type"]
return storage
def change2(storage,func,**kwargs):
self.write_file(func,f'data modify {storage}.value set from storage {defualt_STORAGE} stack_frame[-1].return[-1].value\n',**kwargs)
x.append(change2)
x.append(change)
returnValue = self.preSubscript(i,func,True,x,**kwargs)
elif isinstance(tree.value,ast.Attribute):
# 函数返回值 赋值
value = self.Expr(ast.Expr(value=tree.value),func,-1,**kwargs)
# if isinstance(value['value'],list) and len(value[0]) >= 2: value = value[0] # 特殊情况 (在获取到 AttributeHandler 中的 inputData)
# python 赋值 主要是查是否为全局变量
for i in tree.targets:
if isinstance(i,ast.Name):
self.py_change_value(i.id,value['value'],False,func,False,index,**kwargs)
self.py_change_value_type(i.id,value['type'],index,False,True,func,**kwargs)
is_global = self.py_get_value_global(i.id,func,index,**kwargs)
# mcf 赋值
if is_global:
self.mcf_modify_value_by_from(f'storage {defualt_STORAGE} stack_frame[0].data[{{"id":"{i.id}"}}].value','set',f'storage {defualt_STORAGE} stack_frame[-1].return[-1].value',func,**kwargs)
self.mcf_modify_value_by_from(f'storage {defualt_STORAGE} stack_frame[-1].data[{{"id":"{i.id}"}}].value','set',f'storage {defualt_STORAGE} stack_frame[-1].return[-1].value',func,**kwargs)
elif isinstance(i,ast.Attribute):
ClassC = ClassCall(self.stack_frame,**kwargs)
StoragePath = ClassC.class_var_to_str(i,func,**kwargs)
self.mcf_modify_value_by_from(f'{StoragePath}','set',f'storage {defualt_STORAGE} stack_frame[-1].return[-1].value',func,**kwargs)
x = ClassC.get_class_var(tree.value,func,**kwargs)
ClassC.modify_class_var(i,func,x["value"],**kwargs)
elif isinstance(i,ast.Subscript):
x = []
def change(storage):
storage["value"] = value["value"]
storage["type"] = value["type"]
return storage
def change2(storage,func,**kwargs):
self.write_file(func,f'data modify {storage} set value {{"value":{value["value"]},"type":{value["type"]}}}\n',**kwargs)
x.append(change2)
x.append(change)
returnValue = self.preSubscript(i,func,True,x,**kwargs)
elif isinstance(tree.value,ast.BoolOp):
self.BoolOP_call(tree.value,func,**kwargs)
# python 赋值 主要是查是否为全局变量
for i in tree.targets:
if isinstance(i,ast.Name):
#
self.py_change_value(i.id,1,False,func,False,index,**kwargs)
self.py_change_value_type(i.id,1,index,True,True,func,**kwargs)
is_global = self.py_get_value_global(i.id,func,index,**kwargs)
# mcf 赋值
if is_global:
self.mcf_change_value_by_scoreboard(f'{defualt_STORAGE} stack_frame[0].data[{{"id":"{i.id}"}}].value',f'#{defualt_NAME}.sys.c.0.pass {scoreboard_objective}','int','1',func,**kwargs)
self.mcf_change_value_by_scoreboard(f'{defualt_STORAGE} stack_frame[-1].data[{{"id":"{i.id}"}}].value',f'#{defualt_NAME}.sys.c.0.pass {scoreboard_objective}','int','1',func,**kwargs)
elif isinstance(i,ast.Attribute):
ClassC = ClassCall(self.stack_frame,**kwargs)
StoragePath = ClassC.class_var_to_str(i,func,**kwargs)
self.mcf_change_value_by_scoreboard(f'{StoragePath[8:]}',f'#{defualt_NAME}.sys.c.0.pass {scoreboard_objective}','int','1',func,**kwargs)
ClassC.modify_class_var(i,func,1,**kwargs)
elif isinstance(i,ast.Subscript):
x = []
def change(storage):
storage["value"] = 1
storage["type"] = "int"
return storage
def change2(storage,func,**kwargs):
self.mcf_change_value_by_scoreboard(storage+'.value',f'#{defualt_NAME}.sys.c.0.pass {scoreboard_objective}','int','1',func,**kwargs)
x.append(change2)
x.append(change)
returnValue = self.preSubscript(i,func,True,x,**kwargs)
self.mcf_old_stack_cover_data(func,**kwargs)
self.mcf_remove_stack_data(func,**kwargs)
elif isinstance(tree.value,ast.Compare):
self.Compare_call(tree.value,func,**kwargs)
# python 赋值 主要是查是否为全局变量
for i in tree.targets:
if isinstance(i,ast.Name):
#
self.py_change_value(i.id,1,True,func,False,index,**kwargs)
self.py_change_value_type(i.id,1,index,True,True,func,**kwargs)
is_global = self.py_get_value_global(i.id,func,index,**kwargs)
# mcf 赋值
if is_global:
self.mcf_store_value_by_run_command(f'storage {defualt_STORAGE} stack_frame[0].data[{{"id":"{i.id}"}}].value',f'int 1',f'scoreboard players get #{defualt_NAME}.sys.c.{(self.stack_frame[-1]["BoolOpTime"])}.pass {scoreboard_objective}',func,**kwargs)
self.mcf_store_value_by_run_command(f'storage {defualt_STORAGE} stack_frame[-1].data[{{"id":"{i.id}"}}].value',f'int 1',f'scoreboard players get #{defualt_NAME}.sys.c.{(self.stack_frame[-1]["BoolOpTime"])}.pass {scoreboard_objective}',func,**kwargs)
elif isinstance(i,ast.Attribute):
ClassC = ClassCall(self.stack_frame,**kwargs)
StoragePath = ClassC.class_var_to_str(i,func,**kwargs)
self.mcf_store_value_by_run_command(StoragePath,f'int 1',f'scoreboard players get #{defualt_NAME}.sys.c.{(self.stack_frame[-1]["BoolOpTime"])}.pass {scoreboard_objective}',func,**kwargs)
ClassC.modify_class_var(i,func,1,**kwargs)
elif isinstance(i,ast.Subscript):
x = []
def change(storage):
storage["value"] = 1
storage["type"] = "int"
return storage
def change2(storage,func,**kwargs):
self.mcf_change_value_by_scoreboard(storage+'.value',f'#{defualt_NAME}.sys.c.0.pass {scoreboard_objective}','int','1',func,**kwargs)
x.append(change2)
x.append(change)
returnValue = self.preSubscript(i,func,True,x,**kwargs)
self.mcf_old_stack_cover_data(func,**kwargs)
self.mcf_remove_stack_data(func,**kwargs)
elif isinstance(tree.value,ast.UnaryOp):
self.UnaryOp_call(tree.value,func,**kwargs)
# python 赋值 主要是查是否为全局变量
for i in tree.targets:
if isinstance(i,ast.Name):
#
self.py_change_value(i.id,1,True,func,False,index,**kwargs)
self.py_change_value_type(i.id,1,index,True,True,func,**kwargs)
is_global = self.py_get_value_global(i.id,func,index,**kwargs)
# mcf 赋值
if is_global:
self.mcf_store_value_by_run_command(f'storage {defualt_STORAGE} stack_frame[0].data[{{"id":"{i.id}"}}].value',f'int 1',f'scoreboard players get #{defualt_NAME}.sys.c.{(self.stack_frame[-1]["BoolOpTime"])}.pass {scoreboard_objective}',func,**kwargs)
self.mcf_store_value_by_run_command(f'storage {defualt_STORAGE} stack_frame[-1].data[{{"id":"{i.id}"}}].value',f'int 1',f'scoreboard players get #{defualt_NAME}.sys.c.{(self.stack_frame[-1]["BoolOpTime"])}.pass {scoreboard_objective}',func,**kwargs)
elif isinstance(i,ast.Attribute):
ClassC = ClassCall(self.stack_frame,**kwargs)
StoragePath = ClassC.class_var_to_str(i,func,**kwargs)
self.mcf_store_value_by_run_command(StoragePath,f'int 1',f'scoreboard players get #{defualt_NAME}.sys.c.{(self.stack_frame[-1]["BoolOpTime"])}.pass {scoreboard_objective}',func,**kwargs)
ClassC.modify_class_var(i,func,1,**kwargs)
elif isinstance(i,ast.Subscript):
x = []
def change(storage):
storage["value"] = 1
storage["type"] = "int"
return storage
def change2(storage,func,**kwargs):
self.mcf_change_value_by_scoreboard(storage+'.value',f'#{defualt_NAME}.sys.c.0.pass {scoreboard_objective}','int','1',func,**kwargs)
x.append(change2)
x.append(change)
returnValue = self.preSubscript(i,func,True,x,**kwargs)
self.mcf_old_stack_cover_data(func,**kwargs)
self.mcf_remove_stack_data(func,**kwargs)
elif isinstance(tree.value,ast.List):
value = self.List(tree.value,func,**kwargs)
for i in tree.targets:
if isinstance(i,ast.Name):
self.py_change_value(i.id,value["value"],False,func,False,index,**kwargs)
self.py_change_value_type(i.id,value["type"],index,True,True,func,**kwargs)
is_global = self.py_get_value_global(i.id,func,index,**kwargs)
if(is_global):
self.write_file(func,f'execute unless score #{defualt_STORAGE}.stack.end {scoreboard_objective} matches 1 run data modify storage {defualt_STORAGE} stack_frame[0].data[{{"id":"{i.id}"}}].value set from storage {defualt_STORAGE} data.list_handler\n',**kwargs)
self.write_file(func,f'execute unless score #{defualt_STORAGE}.stack.end {scoreboard_objective} matches 1 run data modify storage {defualt_STORAGE} stack_frame[-1].data[{{"id":"{i.id}"}}].value set from storage {defualt_STORAGE} data.list_handler\n',**kwargs)
elif isinstance(i,ast.Attribute):
ClassC = ClassCall(self.stack_frame,**kwargs)
StoragePath = ClassC.class_var_to_str(i,func,**kwargs)
self.mcf_modify_value_by_from(f'{StoragePath}','set',f'storage {defualt_STORAGE} data.list_handler',func,**kwargs)
ClassC.modify_class_var(i,func,value["value"],**kwargs)
elif isinstance(i,ast.Subscript):
x = []
def change(storage):
storage["value"] = value["value"]
storage["type"] = value["type"]
return storage
def change2(storage,func,**kwargs):
self.write_file(func,f'data modify {storage}.value set from storage {defualt_STORAGE} data.list_handler\n',**kwargs)
self.write_file(func,f'$data modify {storage}.type set value "list"\n',**kwargs)
x.append(change2)
x.append(change)
returnValue = self.preSubscript(i,func,True,x,**kwargs)
elif isinstance(tree.value,ast.Dict):
value = self.Dict(tree.value,func,**kwargs)
for i in tree.targets:
if isinstance(i,ast.Name):
self.py_change_value(i.id,value["value"],False,func,False,index,**kwargs)
self.py_change_value_type(i.id,value["type"],index,True,True,func,**kwargs)
is_global = self.py_get_value_global(i.id,func,index,**kwargs)
if(is_global):
self.write_file(func,f'execute unless score #{defualt_STORAGE}.stack.end {scoreboard_objective} matches 1 run data modify storage {defualt_STORAGE} stack_frame[0].data[{{"id":"{i.id}"}}].value set from storage {defualt_STORAGE} data.dict_handlerK[-1]\n',**kwargs)
self.write_file(func,f'execute unless score #{defualt_STORAGE}.stack.end {scoreboard_objective} matches 1 run data modify storage {defualt_STORAGE} stack_frame[-1].data[{{"id":"{i.id}"}}].value set from storage {defualt_STORAGE} data.dict_handlerK[-1]\n',**kwargs)
elif isinstance(i,ast.Attribute):
ClassC = ClassCall(self.stack_frame,**kwargs)
StoragePath = ClassC.class_var_to_str(i,func,**kwargs)
self.mcf_modify_value_by_from(f'{StoragePath}','set',f'storage {defualt_STORAGE} data.dict_handlerK[-1]',func,**kwargs)
ClassC.modify_class_var(i,func,value["value"],**kwargs)
elif isinstance(i,ast.Subscript):
x = []
def change(storage):
storage["value"] = value["value"]
storage["type"] = value["type"]
return storage
def change2(storage,func,**kwargs):
self.write_file(func,f'data modify {storage}.value set from storage {defualt_STORAGE} data.dict_handlerK[-1]\n',**kwargs)
self.write_file(func,f'$data modify {storage}.type set value "dict"\n',**kwargs)
x.append(change2)
x.append(change)
returnValue = self.preSubscript(i,func,True,x,**kwargs)
# 类型注解赋值
def AnnAssign(self,tree:ast.AnnAssign,func:str,index:-1,*args,**kwargs):
'''带有类型注释的赋值'''
# tree.annotation
self.Assign(ast.Assign(targets=[tree.target],value=tree.value),func,index,*args,**kwargs)
if not isinstance(tree.target,ast.Attribute):
self.py_change_value_type(tree.target.id,tree.annotation.id,-1,False,True,func,*args,**kwargs)
# 增强分配
def AugAssign(self,tree:ast.AugAssign,func:str,index:-1,*args,**kwargs):
'''变量 赋值操作 += -= /= *='''
value = self.Assign(ast.Assign(targets=[ast.Name(id=tree.target.id)],value=ast.BinOp(left=ast.Name(id=tree.target.id),right=tree.value,op=tree.op)),func,index,*args,**kwargs)
## Global
def Global(self,tree:ast.Global,func:str,index:-1,*args,**kwargs):
'''Global 全局变量 '''
for i in tree.names:
for j in self.stack_frame[0]["data"]:
if j["id"] == i:
self.stack_frame[index]["data"].append({"id":i,"value":j["value"],"is_global":True})
self.write_file(func,f'execute unless score #{defualt_STORAGE}.stack.end {scoreboard_objective} matches 1 run data modify storage {defualt_STORAGE} stack_frame[{index}].data[{{"id":"{j["id"]}"}}].value set from storage {defualt_STORAGE} stack_frame[0].data[{{"id":"{j["id"]}"}}].value\n',**kwargs)
## 运算调用前置
def preBinOp(self,tree:ast.BinOp,op:ast.operator,func:str,index:-1,index2:-1,time=0,*args,**kwargs) -> dict:
value = self.BinOp(tree,op,func,index,index2,time,**kwargs)
returnValue = value.value
data = f'from storage {defualt_STORAGE} data.exp_operation[-1].value'
isConstant = False
if (value.kind == None) or (value.kind[0] == "have_operation"):
#常数获取类型
returnType = self.check_type(value.value)
data = f'value {returnValue}'
if isinstance(returnValue,str): data = f'value "{returnValue}"'
isConstant = True
else:
#变量等获取类型
returnType = value.kind[1]
return {"value":returnValue,"type":returnType,"data":data,"isConstant":isConstant}
# 运算
def BinOp(self,tree:ast.BinOp,op:ast.operator,func:str,index:-1,index2:-1,time=0,*args,**kwargs) -> ast.Constant:
'''运算操作
tree新的树,op操作类型 +-*/
time 处理常量运算
调用完后,并且处理完返回值,需 移除计算数据 (如果返回的值为非常数)
>>> self.mcf_remove_Last_exp_operation(func,**kwargs)
'''
# 类型扩建TODO
##判断左右值
if isinstance(tree.left,ast.BinOp):
tree.left = self.BinOp(tree.left,tree.left.op,func,index,index2,time+1,**kwargs)
if isinstance(tree.right,ast.BinOp):
tree.right = self.BinOp(tree.right,tree.right.op,func,index,index2,time+1,**kwargs)
tree_list:ast = [tree.left,tree.right]
for item in range(2):
# 假如为变量
if isinstance(tree_list[item],ast.Name):
value = self.py_get_value(tree_list[item].id,func,index,**kwargs)
# self.mcf_modify_value_by_value(f'storage {defualt_STORAGE} data.exp_operation','append',{"value":0,"type":"num"},func,**kwargs)
self.mcf_modify_value_by_from(f'storage {defualt_STORAGE} data.exp_operation','append',f'storage {defualt_STORAGE} stack_frame[-1].data[{{"id":"{tree_list[item].id}"}}]',func,**kwargs)
tree_list[item] = ast.Constant(value=value, kind=["is_v",self.py_get_type(tree_list[item].id,index),tree_list[item].id,tree_list[item]])
# 假如为函数返回值
elif isinstance(tree_list[item],ast.Call):
# 函数返回值 赋值
value = self.Expr(ast.Expr(value=tree_list[item]),func,-1,*args,**kwargs)
# self.mcf_modify_value_by_value(f'storage {defualt_STORAGE} data.exp_operation','append',{"value":0,"type":"num"},func,**kwargs)
self.mcf_modify_value_by_from(f'storage {defualt_STORAGE} data.exp_operation','append',f'storage {defualt_STORAGE} stack_frame[-1].return[-1]',func,**kwargs)
tree_list[item] = ast.Constant(value=value['value'], kind=["is_call",value['type']])
elif isinstance(tree_list[item],ast.Subscript):
# 切片赋值
returnValue = self.preSubscript(tree_list[item],func,**kwargs)
storage = returnValue["storage"]
value = returnValue["value"]
self.mcf_modify_value_by_value(f'storage {defualt_STORAGE} data.exp_operation','append',{"value":0,"type":"num"},func,**kwargs)
self.mcf_modify_value_by_from(f'storage {defualt_STORAGE} data.exp_operation[-1].value','set',f'{storage}',func,**kwargs)
tree_list[item] = ast.Constant(value=value, kind=["is_call",None])
elif isinstance(tree_list[item],ast.Attribute):
# 属性
ClassC = ClassCall(self.stack_frame,**kwargs)
StoragePath = ClassC.class_var_to_str(tree_list[item],func,**kwargs)
value = ClassC.get_class_var(tree_list[item],func,**kwargs)
self.mcf_modify_value_by_from(f'storage {defualt_STORAGE} data.exp_operation','append',StoragePath[0:-6],func,**kwargs)
# self.mcf_modify_value_by_value(f'storage {defualt_STORAGE} data.exp_operation','append',{"value":0,"type":"num"},func,**kwargs)
tree_list[item] = ast.Constant(value=value.get('value'), kind=["is_v",value.get('type')])
tree.left,tree.right = (tree_list[0],tree_list[1])
# 常量处理
if isinstance(tree.left,ast.List) and isinstance(tree.right,ast.List):
value = None
return ast.Constant(value=value, kind=["have_operation",self.check_type(value)])
if isinstance(tree.left,ast.Constant) and isinstance(tree.right,ast.Constant):
## mcf 处理
if (tree.left.kind == None) and (tree.right.kind == None ):
#常量
value = self.get_operation(tree.left.value,tree.right.value,op,func,**kwargs)
# if not time:
#
# self.mcf_add_exp_operation(value,func,index,**kwargs)
return ast.Constant(value=value, kind=["have_operation",self.check_type(value)])
# have_operation标记没有涉及到变量的 常量之间的运算
elif (tree.left.kind != None and tree.left.kind[0] == "have_operation" and tree.left.kind[1] != None) and (tree.right.kind != None and tree.right.kind[0] == "have_operation" and tree.right.kind[1] != None):
# 涉及到 已经运算过的式子的之间的运算()
value = self.get_operation(tree.left.value,tree.right.value,op,func,**kwargs)
# if not time:
# self.mcf_add_exp_operation(value,func,index,**kwargs)
return ast.Constant(value=value, kind=["have_operation",self.check_type(value)])
elif (tree.left.kind != None and tree.left.kind[0] == "have_operation" and tree.left.kind[1] != None) and (tree.right.kind == None):
value = self.get_operation(tree.left.value,tree.right.value,op,func,**kwargs)
# if not time:
# self.mcf_add_exp_operation(value,func,index,**kwargs)
return ast.Constant(value=value, kind=["have_operation",self.check_type(value)])
elif (tree.left.kind == None) and (tree.right.kind != None and tree.right.kind[0] == "have_operation" and tree.right.kind[1] != None):
value = self.get_operation(tree.left.value,tree.right.value,op,func,**kwargs)
# if not time:
# self.mcf_add_exp_operation(value,func,index,**kwargs)
return ast.Constant(value=value, kind=["have_operation",self.check_type(value)])
# 涉及到变量
else:
#受变量影响的值
if (tree.left.kind == None or tree.left.kind[0]=="have_operation"):
self.mcf_add_exp_operation(tree.left.value,func,index,**kwargs)
if (tree.right.kind == None or tree.right.kind[0]=="have_operation"):
self.mcf_add_exp_operation(tree.right.value,func,index,**kwargs)
value = self.get_operation(tree.left.value,tree.right.value,op,func,**kwargs)
type1 = tree.left.kind[1] if tree.left.kind != None else self.check_type(tree.left.value)
type2 = tree.right.kind[1] if tree.right.kind != None else self.check_type(tree.right.value)
# 魔术方法
if not self.check_basic_type(type1):
sign = None
if isinstance(op,ast.Add) and self.get_class_function_info(type1,"__add__"): sign = '__add__'
if isinstance(op,ast.Sub) and self.get_class_function_info(type1,"__sub__"): sign = '__sub__'
if isinstance(op,ast.Mult) and self.get_class_function_info(type1,"__mul__"): sign = '__mul__'
if isinstance(op,ast.Div) and self.get_class_function_info(type1,"__truediv__"): sign = '__truediv__'
def call():
mmh = MagicMethodHandler(self.stack_frame)
# 传参
inputArgs = [
f"storage {defualt_STORAGE} data.exp_operation[-1]"
]
value = mmh.main(None,tree.left.kind[1],sign,func,inputArgs,storage=f"storage {defualt_STORAGE} data.exp_operation[-2].value",**kwargs)
self.write_file(func,f'''execute unless score #{defualt_STORAGE}.stack.end {scoreboard_objective} matches 1 run data modify storage {defualt_STORAGE} data.exp_operation[-1] set from storage {defualt_STORAGE} stack_frame[{index}].return[-1]\n''',**kwargs)
self.write_file(func,f'''execute unless score #{defualt_STORAGE}.stack.end {scoreboard_objective} matches 1 run data remove storage {defualt_STORAGE} data.exp_operation[-2]\n''',**kwargs)
return ast.Constant(value=value['value'], kind=['is_v',value['type'],None])
if sign != None: return call()
self.mcf_change_exp_operation(op,func,index,type1,type2,**kwargs)
return ast.Constant(value=value, kind=['is_v',self.check_type(value)])
return ast.Constant(value=None, kind=[None,None])
# 函数定义
def FunctionDef(self,tree:ast.FunctionDef,func:str,index:-1,func2:str,*args,**kwargs):
'''函数定义'''
Return_type = self.GetReturnType(tree,**kwargs)
funcName = func
funcPath = func
#如果是类函数则添加进类数据中
callpath = ''
if func2 != '__main__' and not self.py_check_class_exist(func2.replace('/','/')):
func = func2.replace('/','/') + '/' + funcName
funcPath = func2.replace('/','/') + '/' + funcName
if not kwargs.get("ClassName") or (kwargs.get("ClassName") and kwargs.get('Is_new_function') == True):
callpath = defualt_NAME+":"+func+"/_start"
if kwargs.get("ClassName"): callpath = defualt_NAME+":"+kwargs.get("ClassName")+"/"+func+"/_start"
self.stack_frame[-1]["functions"].append({"id":funcName,"args":[],"call":"_start","type":Return_type,"callPath":callpath})
#读取函数参数
args_list = []
for item in tree.args.args:
if isinstance(item,ast.arg):
if not kwargs.get("ClassName"):
self.stack_frame[-1]["functions"][-1]["args"].append(item.arg)
args_list.append(item.arg)
if kwargs.get("ClassName") and kwargs.get('Is_new_function') != True:
callpath = defualt_NAME+":"+kwargs.get("ClassName")+"/"+func+"/_start"
self.py_get_class_add_function(kwargs.get("ClassName"),[funcName,Return_type,args_list,None,callpath])
kwargs['Is_new_function'] = True
#将该函数存储到栈的变量中
self.py_change_value(funcName,callpath,True,func2,False,index,**kwargs)
self.py_append_tree()
#装饰器处理器
if tree.decorator_list:
for i in tree.decorator_list:
DH = DecoratoHandler(self.stack_frame)
self.stack_frame = DH.main(i,funcName,func,funcPath,**kwargs)
#
if kwargs.get("f2"):
kwargs.pop("f2")
f2 = "_start"
if self.get_func_info(kwargs.get("ClassName"),funcName,**kwargs).get("cached"):
f2 = "_start2"
# 函数注解
if tree.body and \
(isinstance(tree.body[0],ast.Expr) and
isinstance(tree.body[0].value,ast.Constant) and
isinstance(tree.body[0].value.value,str)):
for i in tree.body[0].value.value.split("\n"):
self.write_file(funcPath,f'#{i}\n',f2='_start',**kwargs)
#函数参数初始化
self.write_file(funcPath,f'##函数参数初始化\n',f2=f2,**kwargs)
self.FunctionDef_args_init(tree.args,args_list,funcName,index,f2=f2,**kwargs)
#
self.write_file(funcPath,f'#函数传参赋值\n',**kwargs)
#位置传参
Args = tree.args.args
for i in range(len(Args)):
value = Args[i].arg
self.mcf_modify_value_by_from(f'storage {defualt_STORAGE} stack_frame[-1].data[{{"id":"{value}"}}].value','set',f'storage {defualt_STORAGE} data.call_list[-1][{i}].value',funcPath,**kwargs)
#关键字传参
for i in range(len(Args)):
value = Args[i].arg
self.mcf_modify_value_by_from(f'storage {defualt_STORAGE} stack_frame[-1].data[{{"id":"{value}"}}].value','set',f'storage {defualt_STORAGE} data.call_list[-1][{{"id":"{value}"}}].value',funcPath,**kwargs)
self.write_file(funcPath,f'##函数主体\n',f2=f2,**kwargs)
self.walk(tree.body,funcPath,index,f2=f2,**kwargs)
# 如果无返回,则返回字符串None
if not self.stack_frame[-1]['Is_code_have_end']:
self.Return(ast.Return(value=ast.Constant(value="None", kind=None)),funcPath,f2=f2,**kwargs)
self.write_file(funcPath,f'##函数结尾\n',f2=f2,**kwargs)
# 函数是否为 缓存函数
if f2 == "_start2":
funcName2 = func
func = f'{func}/_start2'
self.mcf_call_function(func,funcPath,False,f'execute unless score #{defualt_STORAGE}.stack.end {scoreboard_objective} matches 1.. run ',**kwargs)
# 若该函数为缓存函数,则存储返回结果
# 内容
self.mcf_modify_value_by_from(f'storage {defualt_STORAGE} stack_frame[-1].dync.arg0','set',f'storage {defualt_STORAGE} stack_frame[-1].key',funcPath,**kwargs)
self.mcf_call_function(f'{funcName2}/dync_{self.stack_frame[0]["dync"]}/_start with storage {defualt_STORAGE} stack_frame[-1].dync',funcPath,False,f'',**kwargs)
kwargs['p'] = f'{funcName2}/dync_{self.stack_frame[0]["dync"]}/'
CachedData = f'storage {defualt_STORAGE} stack_frame[0].CachedFunctions[{{"id":"{funcName2}"}}].value.\'$(arg0)\''
if kwargs.get("ClassName"):
CachedData = f'storage {defualt_STORAGE} stack_frame[0].CachedMethod[{{"id":"{kwargs.get("ClassName")}"}}].value[{{"id":"{funcName2}"}}].value.\'$(arg0)\''
if not self.stack_frame[-1]['Is_code_have_end']:
self.write_file(funcPath,f'## 动态命令\n$data modify {CachedData} set value {{"value":"None"}}\n',inNewFile=True,**kwargs)
else:
self.write_file(funcPath,f'## 动态命令\n$data modify {CachedData} set from storage {defualt_STORAGE} stack_frame[-2].return[-1]\n',inNewFile=True,**kwargs)
# self.mcf_modify_value_by_value(f'storage {defualt_STORAGE} stack_frame[-1].dync','set',{},funcPath,**kwargs)
self.stack_frame[0]["dync"] += 1
self.stack_frame.pop(-1)
# 函数参数处理 参数预先值
def FunctionDef_args_init(self,tree:ast.arguments,args_list:list,func:str,index:-1,*args,**kwargs):
'''函数定义中 参数预先值'''
# 类型扩建TODO
for i in range(-1,-1*len(tree.defaults)-1,-1):
if isinstance(tree.defaults[i],ast.BinOp):
value = self.preBinOp(tree.defaults[i],tree.defaults[i].op,func,index,index-1,**kwargs)
self.py_change_value(args_list[i],value["value"],False,func,False,index,**kwargs)
self.write_file(func,f'execute unless score #{defualt_STORAGE}.stack.end {scoreboard_objective} matches 1 run execute unless data storage {defualt_STORAGE} stack_frame[{index}].data[{{"id":"{args_list[i]}"}}] run data modify storage {defualt_STORAGE} stack_frame[{index}].data[{{"id":"{args_list[i]}"}}].value set {value["data"]}\n',**kwargs)
if not value["isConstant"]: self.mcf_remove_Last_exp_operation(func,**kwargs)
elif isinstance(tree.defaults[i],ast.Constant):
# 常数赋值
self.py_change_value(args_list[i],tree.defaults[i].value,True,func,True,index,**kwargs)
elif isinstance(tree.defaults[i],ast.Name):
# 变量赋值
self.py_change_value2(args_list[i],tree.defaults[i].id,func,True,index,**kwargs)
for i in range(-1,-1*len(tree.args)-1,-1):
ARG = tree.args[i]
try:
if isinstance(ARG.annotation,ast.Constant):
# 常数赋值
self.py_change_value_type(ARG.arg,ARG.annotation.value,-1,False,False,func,*args,**kwargs)
except:
pass
# 表达式调用
def Expr(self,tree:ast.Expr,func:str,index:-1,loopTime=0,*args,**kwargs):
'''函数调用 处理'''
func_name = '' #函数名称
Call = tree.value
matchCondition = False # 是否有匹配项
if isinstance(Call , ast.Call):
if isinstance(Call.func , ast.Name):
matchCondition = True
func_name = Call.func.id
#函数参数赋值
args = self.get_function_args(func_name,**kwargs)
call_name = self.get_function_call_name(func_name,**kwargs)
self.write_file(func,f'\n## 调用函数\n',**kwargs)
self.write_file(func,f'#参数处理\n',**kwargs)
self.mcf_modify_value_by_value(f'storage {defualt_STORAGE} data.call_list','append',[],func,**kwargs)
self.stack_frame[-1]["call_list"] = []
#位置传参
for i in range(len(Call.args)):
self.Expr_set_value(ast.Assign(targets=[ast.Name(id=None)],value=Call.args[i]),func,**kwargs)
#关键字传参
for i in range(len(Call.keywords)):
if isinstance(Call.keywords[i],ast.keyword):
self.Expr_set_value(ast.Assign(targets=[ast.Name(id=Call.keywords[i].arg)],value=Call.keywords[i].value),func,**kwargs)
self.mcf_new_stack_extend(func,**kwargs)
# if(len(Call.args)!=0 or len(Call.keywords) != 0):
# self.mcf_modify_value_by_from(f'storage {defualt_STORAGE} data.call_list','set',f'storage {defualt_STORAGE} data.call_list',func,**kwargs)
## 优先判断该函数是否已存在,若未存在,即可能为类实例化
if self.check_function_exist(func_name,**kwargs):
## mcf
self.write_file(func,f'#函数调用\n',**kwargs)
getprefix = self.get_func_info("",func_name,**kwargs).get("prefix")
callPath = self.get_func_info("",func_name,**kwargs).get("callPath")
prefix = f"execute unless score #{defualt_STORAGE}.stack.end {scoreboard_objective} matches 1 run "+getprefix if getprefix != None else f"execute unless score #{defualt_STORAGE}.stack.end {scoreboard_objective} matches 1 run "
self.mcf_call_function(f'{callPath}',func,True,prefix=prefix,**kwargs)
self.mcf_remove_stack_data(func,**kwargs)
self.write_file(func,f'## 调用结束\n',**kwargs)
else:
self.write_file(func,f'#内置函数/类实例化调用\n',**kwargs)
self.stack_frame[-1]["call_list"] = Call.args
SF = System_function(self.stack_frame,func_name,func,**kwargs)
x = SF.main(**kwargs)
self.mcf_remove_stack_data(func,**kwargs)
self.write_file(func,f'## 调用结束\n',**kwargs)
self.write_file(func,f'execute unless score #{defualt_STORAGE}.stack.end {scoreboard_objective} matches 1 run data remove storage {defualt_STORAGE} data.call_list[-1]\n',**kwargs)
return x
self.write_file(func,f'execute unless score #{defualt_STORAGE}.stack.end {scoreboard_objective} matches 1 run data remove storage {defualt_STORAGE} data.call_list[-1]\n',**kwargs)
if not kwargs.get("ClassName"):
for i in self.stack_frame[0]["functions"]:
if i["id"] == func_name:
return {"value":None,"type":i["type"]}
return {"value":None,"type":None}
elif isinstance(Call.func,ast.Attribute):
matchCondition = True
## 属性处理
attribute_name = None
if isinstance(Call.func.value,ast.Name):
attribute_name = Call.func.value.id
func_name = Call.func.attr
#函数参数赋值
args = self.get_function_args(func_name,**kwargs)
call_name = self.get_function_call_name(func_name,**kwargs)
if(attribute_name!='mc' and not self.py_check_type_is_mc(attribute_name)): #可能为自定义类的方法调用
self.write_file(func,f'\n##函数调用_begin (自定义类的方法调用)\n',**kwargs)
self.write_file(func,f'#参数处理.函数处理\n',**kwargs)
self.mcf_modify_value_by_value(f'storage {defualt_STORAGE} data.call_list','append',[],func,**kwargs)
self.stack_frame[-1]["call_list"] = []
#位置传参
for i in range(len(Call.args)):
self.Expr_set_value(ast.Assign(targets=[ast.Name(id=None)],value=Call.args[i]),func,**kwargs)
#关键字传参
for i in range(len(Call.keywords)):
if isinstance(Call.keywords[i],ast.keyword):
self.Expr_set_value(ast.Assign(targets=[ast.Name(id=Call.keywords[i].arg)],value=Call.keywords[i].value),func,**kwargs)
self.mcf_new_stack_extend(func,**kwargs)
#判断是否为第三方数据包
SF = Custom_function(self.stack_frame,attribute_name,func_name,**kwargs)
x = {"value":None,"type":None}
result = {"value":None,"type":None}
if not SF.main(func,**kwargs):
self.stack_frame[-1]["call_list"] = Call.args
x:dict = self.AttributeHandler(Call.func,func,True,**kwargs)
self.stack_frame[-1]["call_list"] = Call.args
if x.get('ReturnValue'):
try:
Handler = TypeAttributeHandler(self.stack_frame,x['ReturnValue']["value"],x['ReturnValue']["type"],func_name,None,True,storage = x['inputData'])
result = Handler.main(func,**kwargs)
except:
...
elif x.get("haveCallFunc"):
result = x
# result = x
else:
Handler = TypeAttributeHandler(self.stack_frame,x.get('value'),self.check_type(x.get('value')),func_name,None,True)
x = Handler.main(func,**kwargs)
self.mcf_remove_stack_data(func,**kwargs)
self.write_file(func,f'execute unless score #{defualt_STORAGE}.stack.end {scoreboard_objective} matches 1 run data remove storage {defualt_STORAGE} data.call_list[-1]\n',**kwargs)
return result
else:
## mc内置
self.stack_frame[-1]["call_list"] = Call.args
MCF = mc_function(self.stack_frame)
x = MCF.main(func_name,self.stack_frame[-1]["call_list"],func,attribute_name=self.py_return_type_mc(attribute_name),var=attribute_name,**kwargs)
return x
elif isinstance(Call.func , ast.Call):
matchCondition = True
# 调用
if not kwargs.get('IsStoreData'):
value = self.Expr(ast.Expr(value=Call.func),func,-1,loopTime+1,IsStoreData=True,**kwargs)
else:
value = self.Expr(ast.Expr(value=Call.func),func,-1,loopTime+1,**kwargs)
self.mcf_modify_value_by_from(f'storage {defualt_STORAGE} data.call_list[-1][-1].value','set',f'storage {defualt_STORAGE} stack_frame[-1].return[-1].value',func,**kwargs)
self.write_file(func,f'\n## 调用函数\n',**kwargs)
self.write_file(func,f'#参数处理\n',**kwargs)
self.mcf_modify_value_by_value(f'storage {defualt_STORAGE} data.call_list','append',[],func,**kwargs)
self.stack_frame[-1]["call_list"] = []
#位置传参
for i in range(len(Call.args)):
self.Expr_set_value(ast.Assign(targets=[ast.Name(id=None)],value=Call.args[i]),func,**kwargs)
#关键字传参
for i in range(len(Call.keywords)):
if isinstance(Call.keywords[i],ast.keyword):
self.Expr_set_value(ast.Assign(targets=[ast.Name(id=Call.keywords[i].arg)],value=Call.keywords[i].value),func,**kwargs)
self.write_file(func,f'execute unless score #{defualt_STORAGE}.stack.end {scoreboard_objective} matches 1 run data modify storage {defualt_STORAGE} stack_frame append from storage {defualt_STORAGE} temp\n',**kwargs)
self.write_file(func,f'#函数调用\n',**kwargs)
# 动态命令
self.mcf_modify_value_by_from(f'storage {defualt_STORAGE} stack_frame[-1].dync.arg0','set',f'storage {defualt_STORAGE} stack_frame[-2].return[-1].value',func,**kwargs)
self.mcf_call_function(f'{func}/dync_{self.stack_frame[0]["dync"]}/_start with storage {defualt_STORAGE} stack_frame[-1].dync',func,False,f'',**kwargs)
kwargs2 = copy.deepcopy(kwargs)
kwargs2['p'] = f'{func}/dync_{self.stack_frame[0]["dync"]}/'
self.write_file(func,f'## 动态命令\n$function $(arg0)\n',inNewFile=True,**kwargs2)
self.stack_frame[0]["dync"] +=1
if not kwargs.get('IsStoreData'):
self.mcf_remove_stack_data(func,IsStoreData=True,**kwargs)
else:
self.mcf_remove_stack_data(func,**kwargs)
self.write_file(func,f'## 调用结束\n',**kwargs)
elif isinstance(Call , ast.Attribute):
matchCondition = True
#属性 (类)
self.mcf_new_stack_extend(func,**kwargs)
x = {"value":None,"type":None}
if not isinstance(Call.value,ast.Call):
x = {"value":None,"type":None}
try:
Handler = TypeAttributeHandler(
self.stack_frame,
self.py_get_value(Call.value.id,-1,**kwargs),
self.py_get_type(Call.value.id,-1,**kwargs),Call.attr,None,False
)
x = Handler.main(func,True,**kwargs)
except:
...
if x == {"value":None,"type":None}:
# 说明是获取的为变量
ClassC = ClassCall(self.stack_frame,**kwargs)
StoragePath = ClassC.class_var_to_str(Call,func,**kwargs)
self.mcf_modify_value_by_value(f'storage {defualt_STORAGE} stack_frame[-1].return','append',{"value":0,"type":"num"},func,**kwargs)
self.mcf_modify_value_by_from(f'storage {defualt_STORAGE} stack_frame[-1].return[-1].value','set',f'{StoragePath}',func,**kwargs)
x = ClassC.get_class_var(Call,func,**kwargs)
x = {"value":x.get('value'),"type":x.get('type')}
else:
self.mcf_modify_value_by_value(f'storage {defualt_STORAGE} stack_frame[-1].return','append',{"value":x[0],"type":f"{x[1]}"},func,**kwargs)
else:
x:dict = self.AttributeHandler(Call,func,False,**kwargs)
self.mcf_modify_value_by_value(f'storage {defualt_STORAGE} stack_frame[-1].return','append',{"value":0,"type":"num"},func,**kwargs)
self.mcf_modify_value_by_from(f'storage {defualt_STORAGE} stack_frame[-1].return[-1].value','set',f'{x[1].replace("return[-1]","return[-2]")}',func,**kwargs)
# self.mcf_remove_stack_data(func,**kwargs)
self.write_file(func,f'execute unless score #{defualt_STORAGE}.stack.end {scoreboard_objective} matches 1 run data remove storage {defualt_STORAGE} data.call_list[-1]\n',**kwargs)
# self.mcf_remove_stack_data(func,**kwargs)
return x
elif isinstance(Call , ast.BinOp):
value = self.preBinOp(Call,Call.op,func,index,index,**kwargs)
return {"value":value["value"],"type":value["type"]}
# 移除参数集
if matchCondition: self.write_file(func,f'execute unless score #{defualt_STORAGE}.stack.end {scoreboard_objective} matches 1 run data remove storage {defualt_STORAGE} data.call_list[-1]\n',**kwargs)
return {"value":None,"type":None}
# 调用函数时 参数处理器
def Expr_set_value(self,tree:ast.Assign,func,loopTime=0,*args,**kwargs):
'''函数调用 传参\n
参数处理'''
# 类型扩建TODO
if isinstance(tree.value,ast.BinOp):
value = self.preBinOp(tree.value,tree.value.op,func,-1,-1,**kwargs)
for i in tree.targets:
if isinstance(i,ast.Name):
self.py_call_list_append(-1,{"value":value["value"],"id":i.id,"is_constant":False})
self.mcf_modify_value_by_value(f'storage {defualt_STORAGE} data.call_list[-1]','append',{"value":0,"id":f"{i.id}"},func,**kwargs)
self.write_file(func,f'execute unless score #{defualt_STORAGE}.stack.end {scoreboard_objective} matches 1 run data modify storage {defualt_STORAGE} data.call_list[-1][-1].value set {value["data"]}\n',**kwargs)
if not value["isConstant"]: self.mcf_remove_Last_exp_operation(func,**kwargs)
elif isinstance(tree.value,ast.Constant):
# 常数赋值
for i in tree.targets:
if isinstance(i,ast.Name):
self.py_call_list_append(-1,{"value":tree.value.value,"id":i.id,"is_constant":True})
self.mcf_modify_value_by_value(f'storage {defualt_STORAGE} data.call_list[-1]','append',{"value":tree.value.value,"id":f"{i.id}"},func,**kwargs)
elif isinstance(tree.value,ast.Name):
# 变量赋值
for i in tree.targets:
if isinstance(i,ast.Name):
self.py_call_list_append(-1,{"value":self.py_get_value(tree.value.id,func,False,-1,**kwargs),"id":i.id,"is_constant":False},**kwargs)
self.mcf_modify_value_by_from(f'storage {defualt_STORAGE} data.call_list[-1]','append',f'storage {defualt_STORAGE} stack_frame[-1].data[{{"id":"{tree.value.id}"}}]',func,**kwargs)
elif isinstance(tree.value,ast.BoolOp):
for i in tree.targets:
if isinstance(i,ast.Name):
#
self.stack_frame[-1]['condition_time'] += 1
self.mcf_new_stack(func,**kwargs)
self.mcf_new_stack_inherit_data(func,**kwargs)