-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodules.py
executable file
·2294 lines (1856 loc) · 71 KB
/
modules.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
from exceptions import ModuleExceptions, TranspilerExceptions
from chonkytypes import String, Char, Int8, Pointer, Int32, HexInt32, ID, List
from compiler import * # For the Compiler class autocomplete
from numba import jit, njit
import pprint
from lexer import ChLexer
from cparser import ChParser
pprint = pprint.PrettyPrinter(indent=2).pprint
from rich.console import Console
from rich.syntax import Syntax
console = Console()
o_isinstance = isinstance
def isinstance(o1, o2):
if o_isinstance(o1, HexInt32) and o2==Int32\
or o_isinstance(o2, HexInt32) and o1==Int32:
return True
elif o_isinstance(o1, o2):
return True
else:
return False
def rprint(data):
console.print(
Syntax(
str(data),
"Python",
padding=1,
line_numbers=True
)
)
class Module:
BUILT_TYPE = str
class MODULE_TYPES:
'''
FUNCTION -> Function module type
ACTION -> Internal action used in processing
'''
FUNCTION = "Function"
ACTION = "Action"
SPECIAL_ACTION = "Special Action"
SPECIAL_ACTION_FUNC = "Special Action Function"
def __init__(
self,
#type: MODULE_TYPES
):
self.type = "Unknown"
self.built = ""
self.template = ""
self.o1 = False
self.o2 = False
self.o3 = False
def __call__(
self,
tree,
no_construct = False,
op: int = 1
):
if op == 1:
self.o1 = True
elif op == 2:
self.o2 = True
elif op == 3:
self.o3 = True
_values = self.proc_tree(tree)
self.override()
if not no_construct:
return self._constructor(_values)
else:
return _values
# Future
#def optimise(self): pass
optimise = None
# Future: Return true for now
def verify(self): return True
def override(self):
"""
Warning: this should be used with caution since it bypasses the default build structure
"""
pass
# Implemented in module child
def proc_tree(self, tree) -> dict: "Return a dict containing values processed from the tree"
# Format assembly
def _constructor(
self,
arguments: dict
) -> BUILT_TYPE:
if arguments == None:
raise ModuleExceptions.InvalidModuleConstruction(self)
try:
return self.template.format(
**arguments
)
except Exception:
raise Exception(f"In '{self.name}' - Failed to unpack elements. Perhaps you need to set `no_construct` to True to avoid this module's construction?")
class PutCharMod(Module):
name="putchar"
type=Module.MODULE_TYPES.FUNCTION
def __init__(self, compiler_instance):
super().__init__()
self.compiler_instance = compiler_instance
self.raw_template = '''
; load {arg}
ldr r20, #{arg}
'''
self.var_template = '''
; load action cmemb
ldr r1, .cmemb
; {arg} is at {pos}
ldr r11, {pos}
; load from {pos}
ldr r0, $2
jpr r1
'''
self.template = '''
; PUTCHAR
{method}
; output
ldr r5, FFFF0000
stb r20, r5
'''
def proc_tree(self, tree):
#pprint(tree)
# Resolve arguments
resolution_module: Module = self.compiler_instance.get_action('RESOLUT')
arguments = [resolution_module(arg, no_construct=True) for arg in tree]
final = ""
# 0 is the var or val
varval = arguments[0]
if isinstance(varval, ID):
pos = self.compiler_instance.get_variable(varval.value)['pos']
final = self.var_template.format(
arg = varval.value,
pos = pos
)
else:
# Assume we are handling a raw value
if isinstance(varval, Char):
val = str(varval.value) # Raw value must be denoted as int
else:
raise Exception(f"[PUTCHAR] Invalid type supplied, Got: {type(varval)} Expected: 'Char()'")
final = self.raw_template.format(arg = val)
return {"method": final}
@jit()
def optimise(self):
return 2+2
class ResolutionMod(Module):
name="RESOLUT"
type = Module.MODULE_TYPES.ACTION
def __init__(self, compiler_instance):
super().__init__()
self.compiler_instance = compiler_instance
def proc_tree(self, tree):
#pprint(tree)
if tree[0] == 'STRING':
if len(tree[1]['VALUE']) == 1:
return Char(tree[1]['VALUE'])
else:
return List(
values = list(tree[1]['VALUE']),
type=Char
)
elif tree[0] == 'INT':
return Int32(tree[1]['VALUE'])
elif tree[0] == 'HEX':
return HexInt32(tree[1]['VALUE'])
elif tree[0] == 'CHAR':
# if the actual type is string, there will be an array in place of the value
if type(tree[1]['VALUE']) == tuple:
return Char(tree[1]['VALUE'][0])
else:
return Char(tree[1]['VALUE'])
elif tree[0] == 'ID':
return ID(tree[1]['VALUE'])
elif tree[0] == 'POINTER':
return Pointer(tree[1]['ID'])
raise Exception(f"[RESOLUT] Failed to match {tree} is '{tree[0]}' supported?")
class FunctionCallMod(Module):
name="FUNCTION_CALL"
type = Module.MODULE_TYPES.SPECIAL_ACTION
def __init__(self, compiler_instance):
super().__init__()
self.standard = """
; Calling {func}
ldr r0, $3
ldr r23, .{func}
jpr r23
"""
self.template = """
; FUNCTION_CALL
{built}
"""
self.compiler_instance: Compiler = compiler_instance
def proc_tree(self, tree):
#pprint(tree)
namespace = None
funcname = tree['ID'][1]['VALUE']
arguments = tree['FUNCTION_ARGUMENTS']
# console.log(f"[FunctionCallMod] {funcname}({arguments})")
# Check if the function is defined already
if funcname in self.compiler_instance.functions or "NAMESPACE" in tree:
# elif funcname is in an namespaced instance
if "NAMESPACE" in tree:
namespace = tree["NAMESPACE"][1]['VALUE']
if namespace not in self.compiler_instance.namespaces:
raise TranspilerExceptions.NamespaceNotFound(namespace, self.compiler_instance.namespaces)
namespace_instance: Compiler = self.compiler_instance.namespaces[namespace]["object"]
if funcname not in namespace_instance.functions:
print(self.compiler_instance.functions)
raise TranspilerExceptions.UnkownMethodReference(funcname)
func = namespace_instance.functions[funcname]
func_instance = namespace_instance.functions[funcname]['object']
# Update instance locals
# func_instance.variables = {**func_instance.variables, **self.compiler_instance.variables }
# print(self.compiler_instance.namespace)
else:
# Check if the function is a builtin module
func = self.compiler_instance.functions[funcname]
if isinstance(func, Module):
func: Module
# console.log(f"\tModule callback matched, requesting build (optimisation {'enabled' if func.optimise is not None else 'not available'})")
# Request build
built = func(arguments['POSITIONAL_ARGS'])
return {"built": built}
else:
# Get the function's compiler instance
func_instance: Compiler = self.compiler_instance.functions[funcname]['object']
# Update instance locals
func_instance.variables = {**func_instance.variables, **self.compiler_instance.variables }
# Dependencies
resolution_module: Module = func_instance.get_action('RESOLUT')
reassign_module: VariableReAssignMod = func_instance.get_action('VARIABLE_REASSIGNMENT')
assign_module: VariableAssignMod = func_instance.get_action('VARIABLE_ASSIGNMENT')
if arguments:
arguments = arguments['POSITIONAL_ARGS']
# Process supplied arguments
for i, arg in enumerate(func_instance.arguments):
try:
current_supplied_raw = arguments[i]
except IndexError:
print(f"IndexError at '{i}:{funcname}'. Arguments content:{arguments}. Exepcted:{func_instance.arguments.keys()}")
quit(1)
name = arg
argtype = func_instance.arguments[arg]['type']
pos = func_instance.arguments[arg]['pos']
current_supplied = resolution_module(current_supplied_raw, no_construct=True)
# # Debug
# print(current_supplied)
# print(name, argtype, pos)
# #
if isinstance(current_supplied, ID):
var_name = current_supplied.value
var_obj = self.compiler_instance.get_variable(var_name)
var_type = var_obj['type']
if type(var_type) != type(argtype):
raise TranspilerExceptions.TypeMissmatch(
name,
var_type,
argtype,
tree['ID'][-1]
)
if isinstance(var_type, List):
for i, item in enumerate(var_obj['object'].values):
# Construct new tree
new_tree = {
'ID': f"{name}_{i}",
'EXPRESSION': item
}
# Reassign value
new_value_for_var = reassign_module(
new_tree,
redirect=True
)
# Append to instance finals
self.compiler_instance.finished.append(
new_value_for_var
)
else:
# Construct new tree
new_tree = {
'ID': name,
'EXPRESSION': current_supplied_raw
}
if namespace is not None:
# Reassign value
new_value_for_var = reassign_module(
new_tree,
redirect=True,
from_pos = var_obj['pos'],
from_var = var_obj
)
# print(f"NAMESPACE {var_name} {var_obj['pos']} -> {name} {pos}")
else:
# Reassign value
new_value_for_var = reassign_module(
new_tree,
redirect=True
)
# print(new_value_for_var)
# Append to instance finals
self.compiler_instance.finished.append(
new_value_for_var
)
elif isinstance(current_supplied, List):
for i, item in enumerate(current_supplied.values):
# Construct new tree
new_tree = {
'ID': f"{name}_{i}",
'EXPRESSION': (current_supplied.type.abbr_name.upper(), {'VALUE':item})
}
# Reassign value
new_value_for_var = reassign_module(
new_tree,
redirect=True
)
# Append to instance finals
self.compiler_instance.finished.append(
new_value_for_var
)
else:
# Check the type of the supplied argument
if not isinstance(current_supplied, argtype):
raise TranspilerExceptions.TypeMissmatch(
name,
current_supplied,
argtype,
tree['ID'][-1]
)
# Hacky
if type(argtype) != str:
argtype = argtype.abbr_name
# Construct new tree
new_tree = {
'ID': name,
'EXPRESSION': (
argtype.upper(),
{
'VALUE': current_supplied.value
}
)
}
# Reassign value
new_value_for_var = reassign_module(
new_tree,
redirect=True
)
# Append to instance finals
self.compiler_instance.finished.append(
new_value_for_var
)
built = self.standard.format(
func = funcname
)
else:
raise TranspilerExceptions.UnkownMethodReference(funcname)
return {"built":built}
class FunctionDecMod(Module):
name="FUNCTION_DECLARATION"
type = Module.MODULE_TYPES.SPECIAL_ACTION_FUNC
def __init__(self, compiler_instance):
super().__init__()
self.func_template = """
; FUNCTION {name} TAKES {items}
.{name}
; set r1 action to lmemw
ldr r1, .lmemw
; Set ret to r0
ldr r11, {ret_pos}
mov r20, r0
ldr r0, $2
jpr r1
; BODY
{program}
; BODY END
; set r1 action to cmemw
ldr r1, .cmemw
; Load return position
ldr r11, {ret_pos}
; load from return addr
ldr r0, $2
jpr r1
jpr r20
; END FUNCTION {name}
"""
self.template = """
; FUNCTION_DECLARATION
{built}
"""
self.compiler_instance: Compiler = compiler_instance
def proc_tree(self, tree):
line = tree['RETURNS_TYPE'][-1]
funcname = tree['ID']
arguments = tree['FUNCTION_ARGUMENTS']
program = tree['PROGRAM']
returns = tree['RETURNS_TYPE'][1]['VALUE']
if arguments:
arguments = arguments['POSITIONAL_ARGS']
# console.log(f"[FunctionDecMod] {funcname}({arguments}) -> {returns}")
# Need to process the program
instance = self.compiler_instance.new_instance(
tree = program,
variables=self.compiler_instance.variables.copy(),
functions=self.compiler_instance.functions.copy(),
inherit=True
)
# Local dependency
cvariable_module: Module = instance.get_action('VARIABLE_ASSIGNMENT')
# Process variables that the function takes
processed_arguments = {}
var_asm = []
if arguments:
for arg in arguments:
# Hype
name = arg[1]['ID']
type = arg[1]['TYPE']
if type == 'list':
cur_var_asm = cvariable_module(
{
"ID": name,
"TYPE": type,
"EXPRESSION": (type.upper(), {"VALUE": "0"}),
"LEN": arg[1]['LEN'],
"SUBTYPE": arg[1]['SUBTYPE']
},
op = 2
)
else:
cur_var_asm = cvariable_module(
{
"ID": name,
"TYPE": type,
"EXPRESSION": (type.upper(), {"VALUE": "0"})
}
)
var_asm.append(cur_var_asm)
var_dict = instance.get_variable(name)
processed_arguments[name] = var_dict['pos']
# Save arguments to our instance
instance.arguments[name] = var_dict
instance.variables[name] = var_dict
# Run the instance
instance.run()
# Add our constructor to the parent instance
for asm in var_asm:
self.compiler_instance.finished.append(asm)
body = instance.finished
# Allocate an address to store our return addr
position = instance.allocate(4)
built = self.func_template.format(
name = funcname,
program = '\n\t\t'.join('\n'.join(body).split('\n')),
ret_pos = position,
items = processed_arguments
)
self.compiler_instance.create_function(
funcname,
instance,
built
)
# Update our primary instance with the
# new instance's positions and values
self.compiler_instance.sync(instance)
return {"built": built}
class ConditionalMod(Module):
name="CONDITIONAL"
type = Module.MODULE_TYPES.SPECIAL_ACTION
def __init__(self, compiler_instance):
super().__init__()
self.standard = """
; store jump locations
ldr r17, ._if_end_{label}
ldr r16, ._else_end_{label}
{first}
; save value to first var
mov r26, r20
{second}
; save value to second var
mov r30, r20
{comparison}
{code}
; Jump to ._else_end_{label} if code has been run
ldr r17, ._if_end_{label}
ldr r16, ._else_end_{label}
jpr r16
._if_end_{label}
{else_code}
ldr r17, ._if_end_{label}
ldr r16, ._else_end_{label}
._else_end_{label}
"""
self.raw_val_template = '''
ldr r20, {hex}{val}
'''
self.load_var_template = '''
; load action for r1 {action}
ldr r1, .{action}
; store var addr
ldr r11, {addr}
; load from var addr
ldr r0, $2
jpr r1
'''
self.template = """
; CONDITIONAL
{built}
"""
self.compiler_instance: Compiler = compiler_instance
def proc_tree(self, tree):
resolution_module: Module = self.compiler_instance.get_action('RESOLUT')
if_condition = tree['IF'][1]['CONDITION']
if_program = tree['IF'][1]['CODE']
else_pr = None if tree["ELSE"][0] is None else tree["ELSE"]
# Values are stored at 26 and 30
conditionals = {
'EQEQ': 'jprne r17, r26, r30',
'NOT_EQEQ': 'jpre r17, r26, r30',
'LESS': 'jprgt r17, r26, r30',
'GREATER': 'jprlt r17, r26, r30'
}
# Resolve condition
condition = conditionals[if_condition[0]]
# Get a new label index
label_index = self.compiler_instance.new_label()
# Process first and second value
first = resolution_module(if_condition[1], no_construct=True)
second = resolution_module(if_condition[2], no_construct=True)
def get_template(attr):
if type(attr) == ID:
attr: ID
if attr.value not in self.compiler_instance.variables:
raise TranspilerExceptions.UnkownVar(
attr.value,
self.compiler_instance.variables
)
var = self.compiler_instance.get_variable(
attr.value
)
pos = var['pos']
read_type = var['type']
read_actions = {
0: 'cmemw',
1: 'cmemb',
2: 'cmemh',
4: 'cmemw'
}
template = self.load_var_template.format(
action = read_actions[read_type.size],
addr = pos
)
else:
if type(attr) == Char:
template = self.raw_val_template.format(
val = attr.value,
hex = '#'
)
else:
template = self.raw_val_template.format(
val = attr.value,
hex = '#'
)
return template
first_template = get_template(first)
second_template = get_template(second)
# Need to process the if program
instance = self.compiler_instance.new_instance(
tree = if_program,
variables=self.compiler_instance.variables.copy(),
functions=self.compiler_instance.functions.copy(),
inherit=True
)
# Run our if program
instance.run()
# Syncronize instance
self.compiler_instance.sync(instance)
# If else exists
if else_pr is not None:
# Need to process the if program
else_instance = self.compiler_instance.new_instance(
tree = else_pr[1]['CODE'],
variables=self.compiler_instance.variables.copy(),
functions=self.compiler_instance.functions.copy(),
inherit=True
)
# Run our if program
else_instance.run()
# Syncronize else_instance
self.compiler_instance.sync(else_instance)
else_code = ''.join(else_instance.finished)
else:
else_code = '\t\t; No else constructed'
built = self.standard.format(
first = first_template,
second = second_template,
label = label_index,
comparison = condition,
code = ''.join(instance.finished),
else_code = else_code
)
return {"built": built}
class WhileMod(Module):
name="WHILE"
type = Module.MODULE_TYPES.SPECIAL_ACTION
def __init__(self, compiler_instance):
super().__init__()
self.standard = """
; store jump locations
._while_start_{label}
ldr r17, ._while_end_{label}
ldr r16, ._while_start_{label}
{first}
; save value to first var
mov r26, r20
{second}
; save value to second var
mov r30, r20
{comparison}
{code}
; Jump to ._while_end_{label} if code has been run
ldr r17, ._while_end_{label}
ldr r16, ._while_start_{label}
jpr r16
._while_end_{label}
"""
self.raw_val_template = '''
ldr r20, {hex}{val}
'''
self.load_var_template = '''
; load action for r1 {action}
ldr r1, .{action}
; store var addr
ldr r11, {addr}
; load from var addr
ldr r0, $2
jpr r1
'''
self.template = """
; CONDITIONAL
{built}
"""
self.compiler_instance: Compiler = compiler_instance
def proc_tree(self, tree):
resolution_module: Module = self.compiler_instance.get_action('RESOLUT')
if_condition = tree['CONDITION']
if_program = tree['PROGRAM']
# Values are stored at 26 and 30
conditionals = {
'EQEQ': 'jprne r17, r26, r30',
'NOT_EQEQ': 'jpre r17, r26, r30',
'LESS': 'jprgt r17, r26, r30',
'GREATER': 'jprlt r17, r26, r30'
}
# Resolve condition
condition = conditionals[if_condition[0]]
# Get a new label index
label_index = self.compiler_instance.new_label()
# Process first and second value
first = resolution_module(if_condition[1], no_construct=True)
second = resolution_module(if_condition[2], no_construct=True)
def get_template(attr):
if type(attr) == ID:
attr: ID
if attr.value not in self.compiler_instance.variables:
raise TranspilerExceptions.UnkownVar(
attr.value,
self.compiler_instance.variables
)
var = self.compiler_instance.get_variable(
attr.value
)
pos = var['pos']
read_type = var['type']
read_actions = {
1: 'cmemb',
2: 'cmemh',
4: 'cmemw'
}
template = self.load_var_template.format(
action = read_actions[read_type.size],
addr = pos
)
else:
if type(attr) == Char:
template = self.raw_val_template.format(
val = attr.value,
hex = '#'
)
else:
template = self.raw_val_template.format(
val = attr.value,
hex = '#'
)
return template
first_template = get_template(first)
second_template = get_template(second)
# Need to process the if program
instance = self.compiler_instance.new_instance(
tree = if_program,
variables=self.compiler_instance.variables.copy(),
functions=self.compiler_instance.functions.copy(),
inherit=True
)
# Run our if program
instance.run()
# Syncronize instance
self.compiler_instance.sync(instance)
built = self.standard.format(
first = first_template,
second = second_template,
label = label_index,
comparison = condition,
code = ''.join(instance.finished)
)
return {"built": built}
class ForLoopCompileTimeMod(Module):
name="FOR_COMP"
type = Module.MODULE_TYPES.SPECIAL_ACTION
def __init__(self, compiler_instance):
super().__init__()
self.template = """
; CONDITIONAL
{built}
"""
self.compiler_instance: Compiler = compiler_instance
def proc_tree(self, tree):
resolution_module: Module = self.compiler_instance.get_action('RESOLUT')
cvariable_module: Module = self.compiler_instance.get_action('VARIABLE_ASSIGNMENT')
reassign_module: VariableReAssignMod = self.compiler_instance.get_action('VARIABLE_REASSIGNMENT')
iterable = tree['ITERABLE']
var = tree['VARIABLE']
program = tree['PROGRAM']
var_asm = cvariable_module(
{
"ID": var[1]['VALUE'],
"TYPE": "int",
"EXPRESSION": ("INT", {"VALUE": "0"})
}
)
self.compiler_instance.finished.append(var_asm)
iterable_id_obj = resolution_module(iterable, True)
iterable_name = iterable_id_obj.value
iterable_dict = self.compiler_instance.get_variable(iterable_name)
iterable_obj = iterable_dict['object']
iterable_len = iterable_obj.length
for x in range(iterable_len):
# Construct new tree
new_tree = {
'ID': var[1]['VALUE'],
'EXPRESSION': ("INT", {"VALUE": str(x)})
}
# Reassign value
new_value_for_var = reassign_module(
new_tree,
redirect=True
)
self.compiler_instance.finished.append(new_value_for_var)
if program:
self.compiler_instance.run(program)
return {"built": "; built"}
class AdvancedWriteMod(Module):
name="ADVANCED_WRITE"
type = Module.MODULE_TYPES.SPECIAL_ACTION
def __init__(self, compiler_instance):
super().__init__()
self.template = """
; ADVANCED WRITE
{built}
"""
self.var_template = '''
; Load from {addr} for var {var}
ldr r11, {addr}
ldr r0, $3
ldr r2, .{read_action}
jpr r2
mov r{reg}, r20
'''
'''
ldr r11, {var_addr}
ldr r0, $3
ldr r2, .{read_actions[var_type.size]}
jpr r2
'''
self.value_template = '''
ldr r{reg}, #{val}
'''
self.compiler_instance: Compiler = compiler_instance
def proc_tree(self, tree) -> dict:
resolution_module: Module = self.compiler_instance.get_action('RESOLUT')
operations = {
"ADD": "add",
"SUB": "sub",
"MUL": "mult",
"DIV": "div",
"OR": "or",
"XOR": "xor",
"AND": "and",
"RIGHT_SHIFT": "rsh",
"LEFT_SHIFT": "lsh"
}
addr = tree['ADDR']
_type = tree['ID']
value = tree['VALUE']
read_actions = {
1: 'cmemb',
2: 'cmemh',
4: 'cmemw'
}
if value[0] in operations:
first = value[1]
second = value[2]
operation = operations[value[0]]
registers = [18, 19]
# Resolve variables``
first_res = resolution_module(first, no_construct=True)
second_res = resolution_module(second, no_construct=True)