-
Notifications
You must be signed in to change notification settings - Fork 1
/
bos2cob_py3.py
1595 lines (1343 loc) · 47.8 KB
/
bos2cob_py3.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
# Written by ashdnazg https://github.com/ashdnazg/bos2cob
# Extended by Beherith to https://github.com/beyond-all-reason/BARScriptCompiler
# released under the GNU GPL v3 license
import sys
import os.path
from glob import glob
import struct
import cob_file
import argparse
import warnings
warnings.filterwarnings('ignore', 'write lextab module')
from io import StringIO
import pcpp
version = "1.1"
parser = argparse.ArgumentParser()
parser.add_argument("--shortopcodes", action='store_true', help = "Use uint8_t opcodes (EXPERIMENTAL with engine branch CobShortOpCodes)")
parser.add_argument("--dontfold", action='store_true', help = "Disable constant folding optimization")
parser.add_argument("--nopcpp", action='store_true', help = "Fallback to builtin preprocessor instead of pcpp")
parser.add_argument("--dumpast", action='store_true', help = "Dump the parsed syntax tree into a _initial.ast file")
parser.add_argument("--dumppcpp", action='store_true', help = "Dump the results of the pcpp preprocessor")
parser.add_argument("--include", type= str, help = "Additional include directory for pcpp preprocessor")
parser.add_argument("filename", type = str, help= "A bos file to compile, or a directory of bos files to work on, such as ../units/myunit.bos", default= "", nargs='?')
args = parser.parse_args()
#args.filename = "C:/Users/Peti/Documents/My Games/Spring/games/Beyond-All-Reason.sdd/scripts/Raptors/raptora2.bos"
LINEAR_SCALE = 65536
ANGULAR_SCALE = 182
OPCODES = {
'MOVE' : 0x10001000,
'TURN' : 0x10002000,
'SPIN' : 0x10003000,
'STOP_SPIN' : 0x10004000,
'SHOW' : 0x10005000,
'HIDE' : 0x10006000,
'CACHE' : 0x10007000,
'DONT_CACHE' : 0x10008000,
'MOVE_NOW' : 0x1000B000,
'TURN_NOW' : 0x1000C000,
'SHADE' : 0x1000D000,
'DONT_SHADE' : 0x1000E000,
'DONT_SHADOW' : 0x1000E000,
'EMIT_SFX' : 0x1000F000,
'WAIT_FOR_TURN' : 0x10011000,
'WAIT_FOR_MOVE' : 0x10012000,
'SLEEP' : 0x10013000,
'PUSH_CONSTANT' : 0x10021001,
'PUSH_LOCAL_VAR' : 0x10021002,
'PUSH_STATIC' : 0x10021004,
'CREATE_LOCAL_VAR' : 0x10022000,
'POP_LOCAL_VAR' : 0x10023002,
'POP_STATIC' : 0x10023004,
'POP_STACK' : 0x10024000,
'ADD' : 0x10031000,
'SUB' : 0x10032000,
'MUL' : 0x10033000,
'DIV' : 0x10034000,
'MOD' : 0x10034001,
'BITWISE_AND' : 0x10035000,
'BITWISE_OR' : 0x10036000,
'BITWISE_XOR' : 0x10037000,
'BITWISE_NOT' : 0x10038000,
'RAND' : 0x10041000,
'GET_UNIT_VALUE' : 0x10042000,
'GET' : 0x10043000,
'SET_LESS' : 0x10051000,
'SET_LESS_OR_EQUAL' : 0x10052000,
'SET_GREATER' : 0x10053000,
'SET_GREATER_OR_EQUAL' : 0x10054000,
'SET_EQUAL' : 0x10055000,
'SET_NOT_EQUAL' : 0x10056000,
'LOGICAL_AND' : 0x10057000,
'LOGICAL_OR' : 0x10058000,
'LOGICAL_XOR' : 0x10059000,
'LOGICAL_NOT' : 0x1005A000,
'START_SCRIPT' : 0x10061000,
'CALL_SCRIPT' : 0x10062000,
'REAL_CALL' : 0x10062001,
'LUA_CALL' : 0x10062002,
'JUMP' : 0x10064000,
'RETURN' : 0x10065000,
'JUMP_NOT_EQUAL' : 0x10066000,
'SIGNAL' : 0x10067000,
'SET_SIGNAL_MASK' : 0x10068000,
'EXPLODE' : 0x10071000,
'PLAY_SOUND' : 0x10072000,
'SET' : 0x10082000,
'ATTACH_UNIT' : 0x10083000,
'DROP_UNIT' : 0x10084000,
}
if args.shortopcodes:
OPCODES = {
"MOVE" : 0x01,
"TURN" : 0x02,
"SPIN" : 0x03,
"STOP_SPIN" : 0x04,
"SHOW" : 0x05,
"HIDE" : 0x06,
#"CACHE" : 0x07,
#"DONT_CACHE" : 0x08,
"MOVE_NOW" : 0x0B,
"TURN_NOW" : 0x0C,
#"SHADE" : 0x0D,
#"DONT_SHADE" : 0x0E,
"EMIT_SFX" : 0x0F,
"WAIT_FOR_TURN" : 0x11,
"WAIT_FOR_MOVE" : 0x12,
"SLEEP" : 0x13,
"PUSH_CONSTANT" : 0x21,
"PUSH_LOCAL_VAR" : 0x22,
"PUSH_STATIC" : 0x23,
"CREATE_LOCAL_VAR" : 0x24,
"POP_LOCAL_VAR" : 0x25,
"POP_STATIC" : 0x26,
"POP_STACK" : 0x27,
"ADD" : 0x31,
"SUB" : 0x32,
"MUL" : 0x33,
"DIV" : 0x34,
"MOD" : 0x30,
"BITWISE_AND" : 0x35,
"BITWISE_OR" : 0x36,
"BITWISE_XOR" : 0x37,
"BITWISE_NOT" : 0x38,
"ABSOLUTE" : 0x39,
"MINIMUM" : 0x3A,
"MAXIMUM" : 0x3B,
"SIGN" : 0x3C,
"CLAMP" : 0x3D,
"DELTAHEADING" : 0x3E,
"MSINE" : 0x3F,
"MCOSINE" : 0x40,
"RAND" : 0x41,
"GET_UNIT_VALUE" : 0x42,
"GET" : 0x43,
"SET_LESS" : 0x51,
"SET_LESS_OR_EQUAL" : 0x52,
"SET_GREATER" : 0x53,
"SET_GREATER_OR_EQUAL" : 0x54,
"SET_EQUAL" : 0x55,
"SET_NOT_EQUAL" : 0x56,
"LOGICAL_AND" : 0x57,
"LOGICAL_OR" : 0x58,
"LOGICAL_XOR" : 0x59,
"LOGICAL_NOT" : 0x5A,
"START_SCRIPT" : 0x61,
"CALL_SCRIPT" : 0x62,
"REAL_CALL" : 0x63,
"LUA_CALL" : 0x69,
"JUMP" : 0x64,
"RETURN" : 0x65,
"JUMP_NOT_EQUAL" : 0x66,
"SIGNAL" : 0x67,
"SET_SIGNAL_MASK" : 0x68,
"EXPLODE" : 0x71,
"PLAY_SOUND" : 0x72,
"SET" : 0x82,
"ATTACH_UNIT" : 0x83,
"DROP_UNIT" : 0x84,
}
#for i in range(256):
# if i not in OPCODES.values():
# print("case 0x%x:"%(i))
for key in OPCODES:
OPCODES[key] = struct.pack("<L", OPCODES[key])
def get_num(num):
return struct.pack("<L", num)
def get_signed_num(num):
return struct.pack("<l", num)
#case insensitive index
def index(iterable, s):
l = s.lower()
for i, v in enumerate(iterable):
if v.lower() == l:
return i
return -1
OPS = {
'+' : OPCODES['ADD'],
'-' : OPCODES['SUB'],
'*' : OPCODES['MUL'],
'/' : OPCODES['DIV'],
'%' : OPCODES['MOD'],
'&' : OPCODES['BITWISE_AND'],
'|' : OPCODES['BITWISE_OR'],
'<' : OPCODES['SET_LESS'],
'>' : OPCODES['SET_GREATER'],
'==' : OPCODES['SET_EQUAL'],
'<=' : OPCODES['SET_LESS_OR_EQUAL'],
'>=' : OPCODES['SET_GREATER_OR_EQUAL'],
'!=' : OPCODES['SET_NOT_EQUAL'],
'&&' : OPCODES['LOGICAL_AND'],
'||' : OPCODES['LOGICAL_OR'],
'AND' : OPCODES['LOGICAL_AND'],
'and' : OPCODES['LOGICAL_AND'],
'OR' : OPCODES['LOGICAL_OR'],
'or' : OPCODES['LOGICAL_OR'],
}
OPS_PYEVAL = {
"+" : "+",
"-" : "-",
"*" : "*",
"/" : "/",
"&" : "&&",
"|" : "||",
"%" : "%",
}
OPS_PYEVAL_PRECEDENCE = ["%", "*", "/", "+", "-", "|", "&"]
OPS_PRECEDENCE = {
'*' : 1,
'/' : 1,
'%' : 1,
'+' : 2,
'-' : 2,
#'ABS': 2,
'<' : 3,
'>' : 3,
'<=' : 3,
'>=' : 3,
'==' : 4,
'!=' : 4,
'&' : 5,
'|' : 6,
'&&' : 7,
'AND' : 7,
'and' : 7,
'||' : 8,
'OR' : 8,
'or' : 8,
}
UNARY_OPS = {
'NOT' : OPCODES['LOGICAL_NOT'],
'!' : OPCODES['LOGICAL_NOT'],
#'ABS' : OPCODES['ABS'],
}
BOS_EXT = 'bos'
COB_EXT = 'cob'
PRINTED_NODES = {'keyword', 'symbol', 'integerConstant', 'floatConstant', 'identifier',
'argumentList', 'staticVarDec', 'pieceDec', 'localVarDec',
'funcDec', 'funcBody', 'ifStatement', 'whileStatement', 'forStatement',
'callStatement',
'startStatement',
'spinStatement',
'stopSpinStatement',
'turnStatement',
'moveStatement',
'waitForTurnStatement',
'waitForMoveStatement',
'emitSfxStatement',
'sleepStatement',
'hideStatement',
'showStatement',
'explodeStatement',
'signalStatement',
'setSignalMaskStatement',
'setStatement',
'getStatement',
'attachUnitStatement',
'dropUnitStatement',
'returnStatement',
'expression', 'term',
'expressionList'}
def escape(s):
return s.replace('&','&').replace('>','>').replace('<','<').replace('\"','"')
class Node(object):
def __init__(self, node_type, text = None):
self._type = node_type
self._text = text # None if text is None else text.encode('utf-8')
self._children = []
self._note = ""
def add_child(self, child):
self._children.append(child)
def clear(self):
self._children = []
def print_node(self, indent = 0, out_file = sys.stdout, verbose = False):
if verbose or self._type in PRINTED_NODES:
indentation = ' ' * indent
if self._text is not None:
out_file.write("%s<%s> %s </%s> %s\n" %(indentation, self._type, escape(self._text), self._type, self._note))
else:
out_file.write("%s<%s>\n %s" % (indentation, self._type,self._note))
for child in self._children:
child.print_node(indent + 1, out_file=out_file,verbose=verbose)
out_file.write("%s</%s>\n%s" % (indentation, self._typeself._note))
else:
for child in self._children:
child.print_node(indent, out_file=out_file, verbose=verbose)
def term_is_a_signedFloatConstant(self):
if self._type== "term" and len(self._children)==1:
child = self._children[0]
if child._type== "constant" and len(child._children)==1:
child = child._children[0]
if child._type== "signedFloatConstant" and len(child._children)==1:
child = child._children[0]
if child._type== "floatConstant" and len(child._children)==0:
return child
return None
def fold_node(self, depth = 0):
# We need to fold left, fold right and check for parenthesis
foldcount = 0
for child in self._children:
foldcount += child.fold_node(depth +1)
foldedone = True
while(foldedone):
foldedone = False
# Handle Negative
if self._type == "signedFloatConstant" and len(self._children) ==2 and self._children[0]._text == '-':
self._children.pop(0)
self._children[0]._text = '-' + self._children[0]._text
#Handle []
if self._type == "constant" and len(self._children) ==3:
sym1 = self._children[0]._text
sym2 = self._children[2]._text
if sym1 == '[' and sym2 == ']':
self._children.pop(2)
self._children.pop(0)
self._children[0]._children[0]._text = str(float(self._children[0]._children[0]._text) * LINEAR_SCALE)
if sym1 == '<' and sym2 == '>':
self._children.pop(2)
self._children.pop(0)
self._children[0]._children[0]._text = str(float(self._children[0]._children[0]._text) * ANGULAR_SCALE)
if self._type == 'expression' and len(self._children) >=2:
for pyop in OPS_PYEVAL_PRECEDENCE:
i = 0
while (i < len(self._children) - 1):
#for i in range(len(self._children) - 1):
# we always fold into term1 in this case, and delete the next opterm
if (i+1) >= len(self._children):
break
term1 = self._children[i].term_is_a_signedFloatConstant()
if not term1 and self._children[i]._type == 'opterm' and self._children[i]._children[1].term_is_a_signedFloatConstant():
term1 = self._children[i]._children[1].term_is_a_signedFloatConstant()
if term1 is None:
i+=1
continue
opterm = self._children[i+1]
if opterm._children[0]._type != "op" or len(opterm._children) < 2:
i+=1
continue
term2 = opterm._children[1].term_is_a_signedFloatConstant()
if term2 is None:
i+=1
continue
op = opterm._children[0]._children[0]._text
if op != pyop:
i+=1
continue
try:
expr = term1._text + ' ' + op + ' ' + term2._text
result = eval(expr)
if op == '/' and abs(float(result)) < 1 and float(term1._text) !=0:
print ("Warning: A division folding resulted in < 1 result", expr)
raise
term1._text = str(result)
self._children.pop(i+1)
#print("Eval of %s to %f successful"%( expr, result))
foldcount += 1
foldedone = True
except:
i+=1
print ("Warning: Cant evaluate expression", expr)
"""
<term>
<symbol> ( </symbol>
<expression>
<term>
<constant>
<signedFloatConstant>
<floatConstant> 3 </floatConstant>
</signedFloatConstant>
</constant>
</term>
</expression>
<symbol> ) </symbol>
</term>
"""
if self._type == "term" and len(self._children) == 3:
symbolstart = self._children[0]
symbolend = self._children[2]
expression = self._children[1]
if symbolstart._type == "symbol" and symbolend._type == "symbol" and len(expression._children) == 1:
newterm = expression._children[0].term_is_a_signedFloatConstant()
if newterm is not None:
self._children=[expression._children[0]._children[0]]
#print("folded parenthesis")
foldcount += 1
foldedone = True
return foldcount
## looks like we can fold these two into a simple term
def __getitem__(self, i):
return self._children[i]
def __len__(self):
return len(self._children)
def get_children(self):
return self._children
def get_type(self):
return self._type
def get_text(self):
if self._text is None:
return "".join(c.get_text() for c in self._children)
return self._text
def count_descendants(self):
d = 1
for child in self._children:
d += child.count_descendants()
return d
def __repr__(self) -> str:
return f'{self._type}:{self.count_descendants()}/{len(self._children)}:{self._text}'
def parse_string(pump, node):
token = pump.next()
if type(token) == tuple:
token = token[0]
if len(token) == 0:
return False
if token.startswith("\""):
node.add_child(Node('stringConstant', token.strip('\"')))
return True
return False
def parse_int(pump, node):
token = pump.next()
if type(token) == tuple:
token = token[0]
if len(token) == 0:
return False
if token.startswith("0x"):
try:
token = str(int(token, 16))
node.add_child(Node('integerConstant', token))
return True
except:
return False
if token.isdigit():
node.add_child(Node('integerConstant', token))
return True
return False
def parse_identifier(pump, node):
token = pump.next()
if type(token) == tuple:
token = token[0]
if len(token) == 0:
return False
if token[0].isalpha() or token[0] == '_':
node.add_child(Node('identifier', token))
return True
return False
def parse_float(pump, node):
token = pump.next()
if type(token) == tuple:
token = token[0]
if len(token) == 0:
return False
if token.count(".") > 1:
return False
if token.replace(".","").isdigit():
node.add_child(Node('floatConstant', token))
return True
return False
ELEMENTS_DICT = {
'keyword' : ('piece', 'static', 'var', 'while', 'for', 'if', 'else', 'return',
'call', 'start', 'script', 'spin', 'stop', 'turn', 'move', 'wait',
'from', 'to', 'along', 'around', 'x', 'y', 'z', 'axis', 'speed', 'now', 'accelerate', 'decelerate',
'hide', 'show', 'set', 'get', 'explode', 'signal', 'mask', 'emit', 'sfx', 'type', 'sleep',
'attach', 'drop', 'unit', 'rand', 'unknown_unit_value',
'dont', 'cache', 'shade', 'shadow', 'play', 'sound'),
'symbol' : ('{', '}', '(', ')', '[', ']', ',', ';', '+', '-', '*', '/', '%', '&', '|',
'<', '>', '=', '!', 'or', 'and', 'not'),
}
ATOMS_DICT = {
'_integerConstant' : parse_int,
'_floatConstant' : parse_float,
'_stringConstant' : parse_string,
'_identifier' : parse_identifier,
}
PARSER_DICT = {
'_file' : (('_declaration~',),),
'_declaration' : (('_pieceDec',), ('_staticVarDec',), ('_funcDec',),),
'_pieceDec' : (('piece', '_pieceName', '_commaPiece~', ';',),),
'_commaPiece' : ((',', '_pieceName',),),
'_pieceName' : (('_identifier',),),
'_staticVarDec' : (('static', '-', 'var', '_varName', '_commaVar~', ';',),),
'_commaVar' : ((',', '_varName',),),
'_varName' : (('_identifier',),),
'_funcDec' : (('_funcName', '(', '_argumentList', ')', '_statementBlock',),),
'_funcName' : (('_identifier',),),
'_argumentList' : (('_arguments?',),),
'_arguments' : (('_varName', '_commaVar~',),),
'_statement' : (('_keywordStatement', ';',), ('_varStatement', ';',), ('_ifStatement',), ('_whileStatement',), ('_forStatement',), ('_assignStatement', ';',), (';',),),
'_assignStatement' : (('_varName', '=', '_expression',), ('_incStatement',), ('_decStatement',),),
'_incStatement' : (('+', '+', '_varName',),),
'_decStatement' : (('-', '-', '_varName',),),
'_ifStatement' : (('if', '(', '_expression', ')', '_statementBlock', '_elseBlock?',),),
'_elseBlock' : (('else', '_statementBlock',),),
'_whileStatement' : (('while', '(', '_expression', ')', '_statementBlock',),),
'_forStatement' : (('for', '(', '_expression', ';', '_expression', ';', '_expression', ';?', ')', '_statementBlock',),),
'_statementBlock' : (('{', '_statement~', '}',), ('_statement',),),
'_keywordStatement' : (
('_callStatement',),
('_startStatement',),
('_spinStatement',),
('_stopSpinStatement',),
('_turnStatement',),
('_moveStatement',),
('_waitForTurnStatement',),
('_waitForMoveStatement',),
('_emitSfxStatement',),
('_sleepStatement',),
('_hideStatement',),
('_showStatement',),
('_explodeStatement',),
('_signalStatement',),
('_setSignalMaskStatement',),
('_setStatement',),
('_getStatement',),
('_attachUnitStatement',),
('_dropUnitStatement',),
('_returnStatement',),
# ('_breakStatement',),
# ('_continueStatement',),
# ('_soundStatement',),
('_playSoundStatement',),
# ('_stopSoundStatement',),
# ('_missionCommandStatement',),
('_cacheStatement',),
('_dontCacheStatement',),
('_dontShadowStatement',),
('_dontShadeStatement',),
),
'_varStatement' : (('var', '_arguments',),),
'_callStatement' : (('call', '-', 'script', '_funcName', '(', '_expressionList', ')',),),
'_startStatement' : (('start', '-', 'script', '_funcName', '(', '_expressionList', ')',),),
'_spinStatement' : (('spin', '_pieceName', 'around', '_axis', 'speed', '_expression', '_optionalAcceleration'),),
'_optionalAcceleration' : (('_acceleration?',),),
'_acceleration' : (('accelerate', '_expression',),),
'_stopSpinStatement' : (('stop', '-', 'spin', '_pieceName', 'around', '_axis', '_optionalDeceleration',),),
'_optionalDeceleration' : (('_deceleration?',),),
'_deceleration' : (('decelerate', '_expression',),),
'_turnStatement' : (('turn', '_pieceName', 'to', '_axis', '_expression', '_speedNow',),),
'_moveStatement' : (('move', '_pieceName', 'to', '_axis', '_expression', '_speedNow',),),
'_speedNow' : (('now',), ('speed', '_expression',),),
'_waitForTurnStatement' : (('wait', '-', 'for', '-', 'turn', '_pieceName', 'around', '_axis',),),
'_waitForMoveStatement' : (('wait', '-', 'for', '-', 'move', '_pieceName', 'along', '_axis',),),
'_emitSfxStatement' : (('emit', '-', 'sfx', '_expression', 'from', '_pieceName',),),
'_sleepStatement' : (('sleep', '_expression',),),
'_hideStatement' : (('hide', '_pieceName',),),
'_showStatement' : (('show', '_pieceName',),),
'_explodeStatement' : (('explode', '_pieceName', 'type', '_expression',),),
'_signalStatement' : (('signal', '_expression',),),
'_setSignalMaskStatement' : (('set', '-', 'signal','-','mask', '_expression',),),
'_setStatement' : (('set', '_expression', 'to', '_expression',),),
'_getStatement' : (('_get',),),
'_attachUnitStatement' : (('attach', '-', 'unit', '_expression', 'to', '_expression',),),
'_dropUnitStatement' : (('drop', '-', 'unit', '_expression',),),
'_returnStatement' : (('return', '_optionalExpression',),),
'_cacheStatement' : (('cache', '_pieceName',),),
'_dontCacheStatement' : (('dont', '-', 'cache', '_pieceName',),),
'_dontShadowStatement' : (('dont', '-', 'shadow', '_pieceName',),),
'_dontShadeStatement' : (('dont', '-', 'shade', '_pieceName',),),
'_playSoundStatement' : (('play', '-', 'sound', '(', '_stringConstant', '_commaExpression', ')'),),
'_axis' : (('_axisLetter', '-', 'axis'),),
'_axisLetter' : (('x',),('y',),('z',),),
'_expressionList' : (('_expressions?',),),
'_expressions' : (('_expression', '_commaExpression~'),),
'_commaExpression' : ((',', '_expression'),),
'_optionalCommaExpression' : (('_commaExpression?',),),
'_expression' : (('_term', '_opterm~',),),
'_optionalExpression' : (('_expression?',),),
'_term' : (('_get',), ('_rand',), ('(', '_expression', ')',), ('_unaryOp', '_term',), ('_varName',),
('_constant',),),
'_get' : (('get', '_term', '(', '_expression', '_optionalCommaExpression', '_optionalCommaExpression', '_optionalCommaExpression', ')',), ('get', '_term',),),
# '_unitValue' : (('_expression',),),
'_rand' : (('rand', '(' , '_expression', ',', '_expression', ')',),),
'_opterm' : (('_op', '_term',),),
'_op' : (('=', '=',), ('<' , '=',), ('>', '=',), ('!', '=',), ('|', '|',), ('&', '&',), ('+',), ('-',), ('*',), ('/',), ('%',), ('&',), ('|',), ('<',), ('>',), ('OR',), ('AND',),),
'_unaryOp' : (('!',), ('NOT',),),
'_constant' : (('<', '_signedFloatConstant', '>',), ('[', '_signedFloatConstant', ']',), ('_signedFloatConstant',), ('_signedIntegerConstant',), ),
'_signedFloatConstant' : (('-', '_floatConstant',), ('_floatConstant',),),
'_signedIntegerConstant' : (('-', '_integerConstant',), ('_integerConstant',),),
}
AXES = ('x', 'y', 'z')
IGNORED_SYMBOLS = (';','(',')', '{', '}', ',')
IGNORED_KEYWORDS = ('accelerate','decelerate')
class Compiler(object):
def __init__(self, tree, cobVersion = 4):
self._static_vars = []
self._local_vars = []
self._pieces = []
self._functions = []
self._code = b""
self._total_offset = 0
self._functions_code = {}
self._compile_funcs = {
# 'class' : self.parse_class,
'file' : self.parse_file,
'staticVarDec' : self.parse_staticVarDec,
'pieceDec' : self.parse_pieceDec,
'funcDec' : self.parse_funcDec,
'arguments' : self.parse_arguments,
'assignStatement' : self.parse_assignStatement,
'incStatement' : self.parse_incStatement,
'decStatement' : self.parse_decStatement,
'keywordStatement' : self.parse_keywordStatement,
'varStatement' : self.parse_varStatement,
'rand' : self.parse_rand,
'get' : self.parse_get,
'ifStatement' : self.parse_ifStatement,
'whileStatement' : self.parse_whileStatement,
'term' : self.parse_term,
'unaryOp' : self.parse_unaryOp,
'constant' : self.parse_constant,
'expression' : self.parse_expression,
# 'stringConstant' : self.parse_stringConstant,
'symbol' : self.parse_symbol,
'keyword' : self.parse_keyword,
}
self._vars_to_push_opcodes = (
(self._local_vars, OPCODES["PUSH_LOCAL_VAR"]),
(self._static_vars, OPCODES["PUSH_STATIC"]),
(self._pieces, OPCODES["PUSH_CONSTANT"]),
)
self._vars_to_pop_opcodes = (
(self._local_vars, OPCODES["POP_LOCAL_VAR"]),
(self._static_vars, OPCODES["POP_STATIC"]),
)
self._cobVersion = cobVersion
self.parse(tree)
def current_offset(self):
return self._total_offset + len(self._code) // 4
def parse(self, node):
if type(self._code) != type(b""):
pass
node_type = node.get_type()
if node_type in self._compile_funcs:
self._compile_funcs[node_type](node)
if type(self._code) != type(b""):
pass
else:
self.parse_children(node)
if type(self._code) != type(b""):
pass
def parse_children(self, node):
if type(self._code) != type(b""):
pass
if len(node.get_children()) == 0:
raise Exception("node not handled %s: %s" % (node.get_type(),node.get_text()))
for child in node.get_children():
self.parse(child)
def parse_file(self, node):
for child_node in node.get_children():
if child_node[0].get_type() == 'funcDec':
function_name = child_node[0][0].get_text()
if function_name in self._functions:
raise Exception("Function %s already defined. Multiple definitions are not allowed!" % (function_name))
self._functions.append(function_name)
self.parse_children(node)
def parse_staticVarDec(self, node):
static_var_name = node[3].get_text()
if static_var_name in self._static_vars:
raise Exception("Static-var %s already exists. Multiple definitions are not allowed!" % (static_var_name))
self._static_vars.append(static_var_name)
for comma_var in node.get_children()[4:]:
if comma_var.get_type() == 'commaVar':
static_var_name = comma_var[1].get_text()
if static_var_name in self._static_vars:
raise Exception("Static-var %s already exists. Multiple definitions are not allowed!" % (static_var_name))
self._static_vars.append(static_var_name)
def parse_pieceDec(self, node):
piece_name = node[1].get_text()
if piece_name in self._pieces:
raise Exception("Piece name %s already exists. Multiple definitions are not allowed!" % (piece_name))
self._pieces.append(piece_name)
for comma_piece in node.get_children()[2:]:
if comma_piece.get_type() == 'commaPiece':
piece_name = comma_piece[1].get_text()
if piece_name in self._pieces:
raise Exception("Piece name %s already exists. Multiple definitions are not allowed!" % (piece_name))
self._pieces.append(piece_name)
def parse_funcDec(self, node):
del self._local_vars[0:]
self._code = b""
if len(node[2].get_children()) > 0:
self.parse(node[2])
code_len = len(self._code)
self.parse(node[4])
#clean code if empty
if len(self._code) == code_len:
self._code = b""
#insert return if necessary
if self._code[-4:] != OPCODES['RETURN']:
self._code += OPCODES['PUSH_CONSTANT'] + get_num(0)
self._code += OPCODES['RETURN']
self._total_offset += len(self._code) // 4
self._functions_code[node[0].get_text()] = self._code
def parse_varStatement(self, node):
self.parse(node[1])
def parse_arguments(self, node):
if len(node.get_children()) == 0:
return
local_var_name = node[0].get_text()
if local_var_name in self._static_vars:
raise Exception('Static-var named "%s" already exists. You cannot reuse the same name as local variable or function argument!' % (local_var_name))
if local_var_name in self._local_vars:
raise Exception('Local-var named "%s" already exists. Multiple definitions are not allowed!' % (local_var_name))
self._local_vars.append(node[0].get_text())
self._code += OPCODES['CREATE_LOCAL_VAR']
for comma_var in node.get_children()[1:]:
if comma_var.get_type() == 'commaVar':
local_var_name = comma_var[1].get_text()
if local_var_name in self._static_vars:
raise Exception('Static-var named "%s" already exists. You cannot reuse the same name as local variable!' % (local_var_name))
if local_var_name in self._local_vars:
raise Exception('Local-var named "%s" already exists. Multiple definitions are not allowed!' % (local_var_name))
self._local_vars.append(comma_var[1].get_text())
self._code += OPCODES['CREATE_LOCAL_VAR']
def parse_assignStatement(self, node):
if len(node.get_children()) < 3:
self.parse_children(node)
return
self.parse(node[2])
self._code += self.get_variable(node[0].get_text(), False)
def parse_incStatement(self, node):
self._code += b"%s%s%s%s%s" % (self.get_variable(node[2].get_text(), True),
OPCODES['PUSH_CONSTANT'],
get_num(1),
OPCODES['ADD'],
self.get_variable(node[2].get_text(), False))
def parse_decStatement(self, node):
self._code += b"%s%s%s%s%s" % (self.get_variable(node[2].get_text(), True),
OPCODES['PUSH_CONSTANT'],
get_num(1),
OPCODES['SUB'],
self.get_variable(node[2].get_text(), False))
def parse_keywordStatement(self, node):
node = node[0]
#get result needs to be handled separately and removed from the stack
if len(node[0].get_children()) > 0 and node[0][0].get_text() == 'get':
self.parse(node)
self._code += OPCODES['POP_STACK']
return
keyword = node[0].get_text()
i = 0
#fix split keywords
while node[i + 1].get_text() == '-':
keyword += '-%s' % (node[i + 2].get_text())
i += 2
if keyword == 'set' or keyword == 'attach-unit':
children = node.get_children()
else:
children = node.get_children()[::-1]
arguments = []
for child_node in children:
if child_node.get_type() == 'pieceName':
piece_name = child_node.get_text()
piece_index = index(self._pieces, piece_name)
if piece_index < 0:
raise Exception('Piece not found: %s' % (piece_name,))
arguments.append(piece_index)
elif child_node.get_type() == 'funcName':
func_name = child_node.get_text()
func_index = index(self._functions, func_name)
if func_index < 0:
raise Exception("Function not found: %s" % (func_name,))
arguments.append(func_index)
elif child_node.get_type() == 'axis':
arguments.append(AXES.index(child_node[0].get_text()))
elif child_node.get_type() == 'expression':
self.parse(child_node)
elif child_node.get_type() == 'expressionList':
if len(child_node.get_children()) > 0:
self.parse(child_node[0])
arguments.append(len(child_node[0].get_children()))
else:
arguments.append(0)
elif child_node.get_type() == 'speedNow':
if child_node[0].get_text() == 'now':
keyword += "-now"
else:
self.parse(child_node[1])
elif child_node.get_type().startswith('optional'):
if len(child_node.get_children()) == 0:
self._code += OPCODES['PUSH_CONSTANT'] + get_num(0)
else:
self.parse_children(child_node)
#has a dummy arg :(
if keyword == 'attach-unit':
self._code += OPCODES['PUSH_CONSTANT'] + get_num(0)
opcode_name = keyword.upper().replace("-","_")
if opcode_name in OPCODES:
opcode = OPCODES[opcode_name]
else:
raise Exception('Unhandled keyword %s %s' % (keyword, opcode_name))
self._code += opcode + struct.pack("<%dL" % len(arguments), *arguments[::-1])
def parse_get(self, node):
num_expressions = 0
for child_node in node.get_children()[1:]:
if child_node.get_type() == 'expression' or child_node.get_type() == 'term':
self.parse(child_node)
num_expressions += 1
elif child_node.get_type().startswith('optional'):
num_expressions += 1
if len(child_node.get_children()) == 0:
self._code += OPCODES['PUSH_CONSTANT'] + get_num(0)
else:
self.parse_children(child_node)
if num_expressions == 1:
self._code += OPCODES['GET_UNIT_VALUE']
return
self._code += OPCODES['GET']
return
def parse_rand(self, node):
self.parse(node[2])
self.parse(node[4])
self._code += OPCODES['RAND']
return
def parse_ifStatement(self, node):
has_else = len(node.get_children()) > 5
self.parse(node[2])
self._code += OPCODES['JUMP_NOT_EQUAL']
condition_jump = len(self._code)
self._code += get_num(0) #placeholder
self.parse(node[4])
if has_else:
self._code += OPCODES['JUMP']
else_jump = len(self._code)
self._code += get_num(0) #placeholder
self._code = b"%s%s%s" % (self._code[:condition_jump], get_num(self.current_offset()), self._code[condition_jump + 4:])
if has_else:
self.parse(node[5][1])
self._code = b"%s%s%s" % (self._code[:else_jump], get_num(self.current_offset()), self._code[else_jump + 4:])
def parse_expression(self, node):
self.parse(node[0])
if len(node.get_children()) == 1:
return
op_stack = []
for op_term in node.get_children()[1:]:
op = op_term[0].get_text()
while len(op_stack) > 0 and OPS_PRECEDENCE[op_stack[-1]] <= OPS_PRECEDENCE[op]:
self._code += OPS[op_stack.pop()]
self.parse(op_term[1])
op_stack.append(op)
while len(op_stack) > 0:
self._code += OPS[op_stack.pop()]
def parse_whileStatement(self, node):
start = self.current_offset()
self.parse(node[2])
self._code += OPCODES['JUMP_NOT_EQUAL']
condition_jump = len(self._code)
self._code += get_num(0) #placeholder
self.parse(node[4])