-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpcc.py
1380 lines (1238 loc) · 64.6 KB
/
pcc.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
#!/usr/bin/env python3
##
## pcc.py
## PIGS C compiler
##
import sys, argparse, re, collections
from pathlib import PurePath, Path
from pycparser import c_ast
from pycparser.c_parser import CParser
from pycparser.plyparser import ParseError
SCR0 = 'v0' ## General purpose (scratch) register
ARG_REGS = ('v1', 'v2', 'v3') ## Function argument register (ARG0 ... ARG2)
class PccError(Exception):
def __init__(self, node, message):
super().__init__(message)
self.node = node
## ---------------------------------------------------------------------------
class AsmVar:
def __init__(self, var_sym=None):
self.vm_var_id = None ## None (unbound) or str "v0" ... "v149"
self.var_sym = var_sym ## VmVariableSymbol var_sym, 1:1 relationship
self.unbound_id = None ## str, fallback-id for unbound variables
def bind(self, vm_var_nr):
self.vm_var_id = f'v{vm_var_nr}'
_unbound_counter = 0
def __str__(self):
if self.vm_var_id is not None:
return self.vm_var_id
elif self.unbound_id is None:
AsmVar._unbound_counter += 1
self.unbound_id = f'<UNBOUND_VARIABLE_{AsmVar._unbound_counter}>'
return self.unbound_id
class AsmStatement:
def __init__(self, comment=None):
self.comment = comment ## None or str, optional comment
def format_statement(self):
raise NotImplementedError()
class AsmTag(AsmStatement):
def __init__(self):
super().__init__()
self.vm_tag_id = None ## None (unbound) or str "1", "2", ..., any unique positive integer
self.unbound_id = None ## str, fallback-id for unbound TAG labels
def format_statement(self):
return f'TAG {self}'
def bind(self, vm_tag_id):
self.vm_tag_id = str(vm_tag_id)
_unbound_counter = 0
def __str__(self):
if self.vm_tag_id is not None:
return self.vm_tag_id
elif self.unbound_id is None:
AsmTag._unbound_counter += 1
self.unbound_id = f'<UNBOUND_LABEL_{AsmTag._unbound_counter}>'
return self.unbound_id
class AsmCmd(AsmStatement):
def __init__(self, instr, args, comment):
super().__init__(comment=comment)
self.instr = instr ## str, uppercase assembly language instruction
self.args = args ## list(arg), command's arguments of type int, str, AsmVar or AsmTag
def format_statement(self):
return f' {self.instr: <5} {" ".join([str(arg) for arg in self.args])}'
@staticmethod
def tag_instr_idx(instr):
try:
return ('TAG', 'CALL', 'JMP', 'JNZ', 'JZ', 'JP', 'JM').index(instr)
except ValueError:
return -1
class AsmBranchCmd(AsmCmd):
pass
class AsmBuffer:
def __init__(self):
self.stmt_buf = [] ## list(AsmStatement asm_stmt)
def __call__(self, instr, *args, comment=None):
instr = instr.upper()
tag_instr_idx = AsmCmd.tag_instr_idx(instr)
if tag_instr_idx < 0: ## any instruction that doesn't expect a single TAG label argument
asm_stmt = AsmCmd(instr, list(args), comment)
elif len(args) != 1 or not isinstance(args[0], AsmTag):
raise Exception(f'internal error: {instr} instruction expects a single AsmTag argument, ' \
f'found: "{" ".join([str(arg) for arg in args])}"')
elif tag_instr_idx == 0: ## TAG <label> instruction (use AsmTag <label> as statement object)
asm_stmt = args[0]
if comment is not None:
asm_stmt.comment = comment
else: ## BRANCH <label> instruction (BRANCH one of JMP, JNZ, ...)
asm_stmt = AsmBranchCmd(instr, list(args), comment)
self.stmt_buf.append(asm_stmt)
def replace_instruction(self, find_instr, replace_instr):
for asm_cmd in self.stmt_buf:
if isinstance(asm_cmd, AsmCmd) and asm_cmd.instr == find_instr:
asm_cmd.instr = replace_instr
def reduce(self):
in_buf = self.stmt_buf
out_buf = [in_buf[0]]
for curr_stmt in in_buf[1:]:
prev_stmt = out_buf[-1]
if isinstance(prev_stmt, AsmCmd) and isinstance(curr_stmt, AsmCmd):
if prev_stmt.instr == 'RET' and curr_stmt.instr == 'RET':
## "RET + <RET>" => drop "RET", keep "<RET>"
continue
elif prev_stmt.instr == 'JMP' and curr_stmt.instr == 'JMP':
## "JMP X + <JMP Y>" => drop "JMP Y", keep "<JMP X>"
continue
elif prev_stmt.instr == 'STA' and curr_stmt.instr == 'LDA' and prev_stmt.args[0] == curr_stmt.args[0]:
## "STA X + <LDA X>" => drop "<LDA Y>", keep "STA X"
continue
elif isinstance(prev_stmt, AsmTag) and isinstance(curr_stmt, AsmTag):
## "TAG X + <TAG Y>" => replace all uses of "Y" with "X", keep "TAG X", drop "TAG Y"
self._replace_tag(curr_stmt, prev_stmt)
continue
elif isinstance(prev_stmt, AsmTag) and isinstance(curr_stmt, AsmCmd) and curr_stmt.instr == 'JMP':
if len(out_buf) > 2 and isinstance(out_buf[-2], AsmCmd) and out_buf[-2].instr == 'JMP':
## "JMP Z + TAG X + <JMP Y>" => replace all uses of "X" with "Y", drop both "TAG X" and "<JMP Y>"
self._replace_tag(prev_stmt, curr_stmt.args[0])
del out_buf[-1]
continue
else:
## "TAG X + <JMP Y>" => replace all uses of "X" with "Y", drop "TAG X", keep "<JMP Y>"
self._replace_tag(prev_stmt, curr_stmt.args[0])
out_buf[-1] = curr_stmt
continue
elif isinstance(prev_stmt, AsmCmd) and isinstance(curr_stmt, AsmTag):
if prev_stmt.instr == 'JMP' and prev_stmt.args[0] == curr_stmt:
## "JMP X + <TAG X>" => drop "JMP X", keep "<TAG X>"
out_buf[-1] = curr_stmt
continue
out_buf.append(curr_stmt)
self.stmt_buf = out_buf
def drop_unused_tags(self, tag_use_count):
for asm_stmt in self.stmt_buf:
if isinstance(asm_stmt, AsmTag) and asm_stmt not in tag_use_count:
tag_use_count[asm_stmt] = 0
elif isinstance(asm_stmt, AsmBranchCmd):
asm_tag = asm_stmt.args[0]
if asm_tag not in tag_use_count:
tag_use_count[asm_tag] = 1
else:
tag_use_count[asm_tag] += 1
## drop TAG-commands of tags that are not used in any branch-command
self.stmt_buf = [asm_stmt for asm_stmt in self.stmt_buf
if not isinstance(asm_stmt, AsmTag) or tag_use_count[asm_stmt] != 0]
def bind_tags(self, tag_id_offset):
tag_counter = 0
for asm_tag in self.stmt_buf:
if isinstance(asm_tag, AsmTag):
asm_tag.bind(tag_id_offset + tag_counter)
tag_counter += 1
return tag_counter
def collect_vm_variables(self, global_asm_vars, local_asm_vars):
for asm_cmd in self.stmt_buf:
if isinstance(asm_cmd, AsmCmd):
for asm_var in asm_cmd.args:
if isinstance(asm_var, AsmVar):
if asm_var.var_sym.context_function is None:
global_asm_vars[asm_var] = True
else:
local_asm_vars[asm_var] = True
def _replace_tag(self, find_tag, replace_tag):
for asm_cmd in self.stmt_buf:
if isinstance(asm_cmd, AsmBranchCmd) and asm_cmd.args[0] is find_tag:
asm_cmd.args[0] = replace_tag
## ---------------------------------------------------------------------------
class EmulatedInstrs:
EMULATED_INSTR = {
'NEG': 'int NEG(): A=-A; F=A',
'NOT': 'int NOT(): A=~A; F=A',
'NOTL': 'int NOTL(): A=!A; A:(0|1)',
'ANDL': f'int ANDL({SCR0}): A=(A && {SCR0}); A:(0|1)',
'ORL': f'int ORL({SCR0}): A=(A || {SCR0}); A:(0|1)',
'EQ': f'int EQ({SCR0}): A=(A == {SCR0}); A:(0|1)',
'NE': f'int NE({SCR0}): A=(A != {SCR0}); A:(0|1)',
'GT': f'int GT({SCR0}): A=(A > {SCR0}); A:(0|1)',
'GE': f'int GE({SCR0}): A=(A >= {SCR0}); A:(0|1)',
'LT': f'int LT({SCR0}): A=(A < {SCR0}); A:(0|1)',
'LE': f'int LE({SCR0}): A=(A <= {SCR0}); A:(0|1)' }
INLINED_INSTR = ('NEG', 'NOT')
class InstrFunc:
def __init__(self, instr, asm_tag, asm_buf):
self.instr = instr ## str, emulated instruction name
self.asm_tag = asm_tag ## AsmTag, emulator function entry point's TAG
self.asm_buf = asm_buf ## AsmBuffer, emulator function body's statement buffer
self.caller = set() ## set(str func_name), set of calling function names
def __init__(self):
self.instr_funcs = {} ## dict(str instr: InstrFunc instr_func), emulated instructions
def is_emulated(self, instr):
return instr in self.EMULATED_INSTR
def drop_caller(self, func_names_dropped):
drop_instrs = []
for instr, instr_func in self.instr_funcs.items():
instr_func.caller -= func_names_dropped
if len(instr_func.caller) == 0:
drop_instrs.append(instr)
for instr in drop_instrs:
del self.instr_funcs[instr]
def asm_bufs(self):
return [instr_func.asm_buf for instr_func in self.instr_funcs.values()]
def compile(self, cc, instr): ## A := instr(A); F := undef
if instr not in self.instr_funcs:
if instr in self.INLINED_INSTR:
getattr(self, f'_compile_{instr}_inline')(cc.asm_out)
return
asm_tag = AsmTag()
asm_out = AsmBuffer()
asm_out('TAG', asm_tag, comment=self.EMULATED_INSTR[instr])
getattr(self, f'_compile_{instr}_definition')(asm_out)
asm_out('RET')
self.instr_funcs[instr] = self.InstrFunc(instr, asm_tag, asm_out)
instr_func = self.instr_funcs[instr]
func_name = cc.context_function.func_name if cc.context_function is not None else '.init'
instr_func.caller.add(func_name)
cc.asm_out('CALL', instr_func.asm_tag, comment=instr)
def _compile_NEG_inline(self, asm_out):
asm_out('XOR', '0xffffffff') ## A := A ^ 0xffffffff
asm_out('ADD', 1) ## A := A + 1; F := A
def _compile_NOT_inline(self, asm_out):
asm_out('XOR', '0xffffffff') ## A := A ^ 0xffffffff; F := A
def _compile_NOTL_definition(self, asm_out):
true_tag = AsmTag()
asm_out('OR', 0, comment='F=A') ## assert F := A before conditional jump
asm_out('JZ', true_tag) ## IF (F == 0) GOTO true_tag
asm_out('LDA', 0)
asm_out('RET') ## return FALSE
asm_out('TAG', true_tag) ## true_tag: return TRUE
asm_out('LDA', 1)
def _compile_ANDL_definition(self, asm_out):
ret_tag = AsmTag()
asm_out('OR', 0, comment='F=A') ## assert F := A before conditional jump
asm_out('JZ', ret_tag) ## IF (F == 0) GOTO ret_tag
asm_out('LDA', SCR0)
asm_out('OR', 0, comment='F=A') ## assert F := A before conditional jump
asm_out('JZ', ret_tag) ## IF (F == 0) GOTO ret_tag
asm_out('LDA', 1)
asm_out('TAG', ret_tag) ## ret_tag: return TRUE or FALSE
def _compile_ORL_definition(self, asm_out):
true_tag = AsmTag()
asm_out('OR', SCR0) ## A := A | SCR0, F := A
asm_out('JNZ', true_tag) ## IF (F != 0) GOTO true_tag
asm_out('RET') ## return FALSE
asm_out('TAG', true_tag) ## true_tag: return TRUE
asm_out('LDA', 1)
def _compile_EQ_definition(self, asm_out):
true_tag = AsmTag()
asm_out('CMP', SCR0) ## F := A - SCR0
asm_out('JZ', true_tag) ## IF (F == 0) GOTO true_tag
asm_out('LDA', 0)
asm_out('RET') ## return FALSE
asm_out('TAG', true_tag) ## true_tag: return TRUE
asm_out('LDA', 1)
def _compile_NE_definition(self, asm_out):
true_tag = AsmTag()
asm_out('CMP', SCR0) ## F := A - SCR0
asm_out('JNZ', true_tag) ## IF (F != 0) GOTO true_tag
asm_out('LDA', 0) ## A := 0
asm_out('RET') ## return FALSE
asm_out('TAG', true_tag) ## true_tag: return TRUE
asm_out('LDA', 1)
def _compile_GT_definition(self, asm_out):
false_tag = AsmTag()
asm_out('CMP', SCR0) ## F := A - SCR0
asm_out('JZ', false_tag) ## IF (F == 0) GOTO false_tag
asm_out('JM', false_tag) ## IF (F < 0) GOTO false_tag
asm_out('LDA', 1)
asm_out('RET') ## return TRUE
asm_out('TAG', false_tag) ## false_tag: return FALSE
asm_out('LDA', 0)
def _compile_GE_definition(self, asm_out):
true_tag = AsmTag()
asm_out('CMP', SCR0) ## F := A - SCR0
asm_out('JP', true_tag) ## IF (F >= 0) GOTO true_tag
asm_out('LDA', 0)
asm_out('RET') ## return FALSE
asm_out('TAG', true_tag) ## true_tag: return TRUE
asm_out('LDA', 1)
def _compile_LT_definition(self, asm_out):
true_tag = AsmTag()
asm_out('CMP', SCR0) ## F := A - SCR0
asm_out('JM', true_tag) ## IF (F < 0) GOTO true_tag
asm_out('LDA', 0)
asm_out('RET') ## return FALSE
asm_out('TAG', true_tag) ## true_tag: return TRUE
asm_out('LDA', 1)
def _compile_LE_definition(self, asm_out):
true_tag = AsmTag()
asm_out('CMP', SCR0) ## F := A - SCR0
asm_out('JZ', true_tag) ## IF (F == 0) GOTO true_tag
asm_out('JM', true_tag) ## IF (F < 0) GOTO true_tag
asm_out('LDA', 0)
asm_out('RET') ## return FALSE
asm_out('TAG', true_tag) ## true_tag: return TRUE
asm_out('LDA', 1)
## ---------------------------------------------------------------------------
class FunctionPrototype:
def __init__(self, decl_node, is_vm_function):
arg_ctypes = []
func_args = decl_node.type.args
if func_args is not None and not (len(func_args.params) == 1 and
self._parse_ctype(func_args.params[0].type, accept_void=True, accept_uint=is_vm_function) == 'void'):
for arg in func_args.params:
arg_ctypes.append(self._parse_ctype(arg.type, accept_uint=is_vm_function))
self.is_vm_function = is_vm_function
self.arg_ctypes = arg_ctypes
self.ret_ctype = self._parse_ctype(decl_node.type.type, accept_void=True, accept_uint=is_vm_function)
def matches(self, other):
return self.is_vm_function == other.is_vm_function and \
self.arg_ctypes == other.arg_ctypes and \
self.ret_ctype == other.ret_ctype
def _parse_ctype(self, node, accept_void=False, accept_uint=False):
if isinstance(node.type, c_ast.IdentifierType):
type_names = node.type.names
if len(type_names) == 1:
type_name = type_names[0]
if type_name in ('int', 'long'):
return type_name
elif accept_void and type_name == 'void':
return type_name
elif accept_uint and type_name == 'unsigned':
return type_name
elif len(type_names) == 2:
if accept_uint and type_names[0] == 'unsigned' and type_names[1] in ('int', 'long'):
return ' '.join(type_names)
raise PccError(node.type, f'unsupported type "{" ".join(type_names)}"')
raise PccError(node.type, 'unsupported type')
class Function:
def __init__(self, decl_node, prototype):
self.decl_node = decl_node
self.func_name = decl_node.name
self.prototype = prototype
self.arg_count = len(prototype.arg_ctypes)
self.has_return = prototype.ret_ctype != 'void'
def decl_str(self):
return f'{self.prototype.ret_ctype} {self.func_name}({", ".join(self.prototype.arg_ctypes)})'
def asm_repr(self):
raise NotImplementedError()
class UserDefFunction(Function):
def __init__(self, decl_node, prototype):
super().__init__(decl_node, prototype)
if self.func_name == 'main':
## check main() function prototype constraints
if self.has_return:
raise PccError(decl_node, 'return type other than "void" is not supported for main()')
elif self.arg_count > 0:
raise PccError(decl_node, 'function arguments are not supported for main()')
self.impl_node = None ## None or c_ast.FuncDef, function implementation's AST node
self.caller = set() ## set(str func_name), set of calling function names
self.asm_tag = AsmTag() ## AsmTag, str() expands to function entry point's TAG
self.asm_buf = AsmBuffer() ## AsmBuffer, function implementation's statement buffer
self.arg_vars = [ ## list(AsmVar), function argument VM variables
AsmVar() for i in range(self.arg_count)]
self.static_asm_tags = {} ## dict(str tag_label: AsmTag asm_tag), user-defined static tags
def asm_repr(self):
return self.asm_tag
class VmApiFunction(Function):
VM_FUNCTION_INSTR_CIS = {
'gpioSetMode': 'MODES', ## Basic commands
'gpioGetMode': 'MODEG',
'gpioSetPullUpDown': 'PUD',
'gpioRead': 'READ',
'gpioWrite': 'WRITE',
'gpioPWM': 'PWM', ## PWM commands
'gpioSetPWMfrequency': 'PFS',
'gpioSetPWMrange': 'PRS',
'gpioGetPWMdutycycle': 'GDC',
'gpioGetPWMfrequency': 'PFG',
'gpioGetPWMrange': 'PRG',
'gpioGetPWMrealRange': 'PRRG',
'gpioServo': 'SERVO', ## Servo commands
'gpioGetServoPulsewidth': 'GPW',
'gpioTrigger': 'TRIG', ## Intermediate commands
'gpioSetWatchdog': 'WDOG',
'gpioRead_Bits_0_31': 'BR1',
'gpioRead_Bits_32_53': 'BR2',
'gpioWrite_Bits_0_31_Clear': 'BC1',
'gpioWrite_Bits_32_53_Clear': 'BC2',
'gpioWrite_Bits_0_31_Set': 'BS1',
'gpioWrite_Bits_32_53_Set': 'BS2',
'gpioNotifyOpen': 'NO', ## Advanced commands
'gpioNotifyClose': 'NC',
'gpioNotifyBegin': 'NB',
'gpioNotifyPause': 'NP',
'gpioHardwareClock': 'HC',
'gpioHardwarePWM': 'HP',
'gpioGlitchFilter': 'FG',
'gpioNoiseFilter': 'FN',
'gpioSetPad': 'PADS',
'gpioGetPad': 'PADG',
'eventMonitor': 'EVM', ## Event commands
'eventTrigger': 'EVT',
'i2cOpen': 'I2CO', ## I2C commands
'i2cClose': 'I2CC',
'i2cWriteQuick': 'I2CWQ',
'i2cReadByte': 'I2CRS',
'i2cWriteByte': 'I2CWS',
'i2cReadByteData': 'I2CRB',
'i2cWriteByteData': 'I2CWB',
'i2cReadWordData': 'I2CRW',
'i2cWriteWordData': 'I2CWW',
'i2cProcessCall': 'I2CPC',
'gpioHardwareRevision': 'HWVER', ## Utility commands
'gpioDelay_us': 'MICS',
'gpioDelay_ms': 'MILS',
'gpioVersion': 'PIGPV',
'gpioTick': 'TICK',
'gpioCfgGetInternals': 'CGI', ## Configuration commands
'gpioCfgSetInternals': 'CSI',
'gpioWait': 'WAIT', ## Script-exclusive commands
'eventWait': 'EVTWT',
'exit': 'HALT' }
VM_FUNCTION_INSTR_EIS = {
'gpioSetMode': 'MI', ## EIS: normal prototype MI x1 x2
'gpioSetPullUpDown': 'PUDI' } ## EIS: normal prototype PUDI x1 x2
def __init__(self, decl_node, prototype, use_cis):
super().__init__(decl_node, prototype)
self.use_cis = use_cis
self.instr = None
if use_cis:
self.map_argument = getattr(self, f'_map_argument_cis_{self.func_name}', None)
def asm_repr(self):
if self.instr is None:
func_name = self.func_name
if not self.use_cis and func_name in self.VM_FUNCTION_INSTR_EIS:
self.instr = self.VM_FUNCTION_INSTR_EIS[func_name]
else:
if func_name not in self.VM_FUNCTION_INSTR_CIS:
raise PccError(self.decl_node, f'undefined VM function "{func_name}"')
self.instr = self.VM_FUNCTION_INSTR_CIS[func_name]
return self.instr
def _map_argument_cis_gpioSetMode(self, node, i_arg, const_arg):
if i_arg == 1:
## int gpioSetMode(unsigned gpio, unsigned mode), 2nd argument "mode":
## index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7
## vm_api.h | PI_INPUT | PI_OUTPUT | PI_ALT5 | PI_ALT4 | PI_ALT0 | PI_ALT1 | PI_ALT2 | PI_ALT3
## MODES g m | "R" | "W" | "5" | "4" | "0" | "1" | "2" | "3"
if const_arg is None:
raise PccError(node, f'{self.decl_str()}: compile-time constant required for 2nd argument')
const_int = int(const_arg, 0)
if const_int >= 0 and const_int <= 7:
const_arg = 'RW540123'[const_int]
return const_arg
def _map_argument_cis_gpioSetPullUpDown(self, node, i_arg, const_arg):
if i_arg == 1:
## int gpioSetPullUpDown(unsigned gpio, unsigned pud), 2nd argument "pud":
## index | 0 | 1 | 2
## vm_api.h | PI_PUD_OFF | PI_PUD_DOWN | PI_PUD_UP
## PUD g p | "O" | "D" | "U"
if const_arg is None:
raise PccError(node, f'{self.decl_str()}: compile-time constant required for 2nd argument')
const_int = int(const_arg, 0)
if const_int >= 0 and const_int <= 2:
const_arg = 'ODU'[const_int]
return const_arg
## ---------------------------------------------------------------------------
class AbstractSymbol:
def __init__(self, cname):
self.cname = cname ## str cname, symbol's C name in scope
def asm_repr(self): ## returns str, AsmVar or AsmTag, only types
raise NotImplementedError() ## that properly expand themselves with str()
class EnumSymbol(AbstractSymbol):
def __init__(self, cname, const_value):
super().__init__(cname)
self.const_value = const_value
def asm_repr(self): ## str const_value, integer represented as str
return self.const_value
class VariableSymbol(AbstractSymbol):
def __init__(self, ctype, cname):
super().__init__(cname)
self.ctype = ctype
class VmVariableSymbol(VariableSymbol):
def __init__(self, ctype, cname, asm_var, decl_node, context_function):
super().__init__(ctype, cname)
if asm_var is None:
self.asm_var = AsmVar(var_sym=self)
else:
if asm_var.var_sym is not None:
raise Exception('internal error: AsmVar is already bound to a VariableSymbol')
asm_var.var_sym = self
self.asm_var = asm_var
self.decl_node = decl_node
self.context_function = context_function
def asm_repr(self): ## AsmVar asm_var, str() expands to VM variable name ("vN")
return self.asm_var
class VmParameterSymbol(VariableSymbol):
def __init__(self, ctype, cname, asm_par):
super().__init__(ctype, cname)
self.asm_par = asm_par
def asm_repr(self): ## str asm_par, VM parameter name ("pN")
return self.asm_par
class FunctionSymbol(AbstractSymbol):
def __init__(self, cname, function):
super().__init__(cname)
self.function = function
def asm_repr(self):
return self.function.asm_repr() ## AsmTag asm_tag (user-defined function) or str asm_instr (VM API function)
## ---------------------------------------------------------------------------
class PccLogger:
NON_WHITESPACE_PATTERN = re.compile(r'[^\t ]')
def __init__(self, c_sources, debug, file=sys.stderr):
self.c_sources = c_sources ## CSourceBundle, C sources to compile
self.debug = debug ## bool, True: show extra debug output
self.file = file ## file-like object, log sink
self.error_count = 0 ## int, error counter
self.e_location = None ## tuple(), stores the most recent logged error location
def error_msg(self, flat_row, col, message):
self._log_message(flat_row, col, message)
self.error_count += 1
def error(self, e, context_function=None):
self._log_node_message(e.node, f'error: {e}', context_function)
if e.node is not None and self.debug:
print('Extra debug node information:\n' + str(e.node), file=self.file)
self.error_count += 1
def warning(self, node, message, context_function):
self._log_node_message(node, f'warning: {message}', context_function)
def _log_node_message(self, node, message, context_function):
if node is None:
print(message, file=self.file)
else:
flat_row, col = node.coord.line, node.coord.column
func_name = context_function.func_name if context_function is not None else None
self._log_message(flat_row, col, message, ctx_func_name=func_name)
def _log_message(self, flat_row, col, message, ctx_func_name=None):
filename, row = self.c_sources.map_coord(flat_row)
if filename is None:
error_msg = f':{flat_row}:{col}: {message}'
else:
error_msg = ''
if ctx_func_name is not None:
e_location = (filename, ctx_func_name)
if self.e_location != e_location:
self.e_location = e_location
error_msg = f'{filename}: In function "{ctx_func_name}":\n'
src_line = self.c_sources.line_at(filename, row)
pointer_indent = self.NON_WHITESPACE_PATTERN.sub(src_line[:col-1])
error_msg += f'{filename}:{row}:{col}: {message}\n{src_line}\n{pointer_indent}^^^'
print(error_msg, file=self.file)
## ---------------------------------------------------------------------------
class AstCompiler:
UNARY_OP_INSTR = { ## 3 arithmetic + 1 logical ops
'+': None, ## A=+A; F=undef/A (CIS/EIS)
'-': 'NEG', ## A=-A; F=undef/A (CIS/EIS)
'~': 'NOT', ## A=~A; F=undef/A (CIS/EIS)
'!': 'NOTL' } ## A=!A; F=undef/A (CIS/EIS); A:(0|1)
BINARY_OP_INSTR = { ## 10 arithmetic + 2 logical + 6 comparison ops
'+': 'ADD', ## A+=x; F=A
'-': 'SUB', ## A-=x; F=A
'*': 'MLT', ## A*=x; F=A
'/': 'DIV', ## A/=x; F=A
'%': 'MOD', ## A%=x; F=A
'&': 'AND', ## A&=x; F=A
'|': 'OR', ## A|=x; F=A
'^': 'XOR', ## A^=x; F=A
'<<': 'RLA', ## A<<=x; F=A
'>>': 'RRA', ## A>>=x; F=A
'&&': 'ANDL', ## A=(A && x); F=undef/A (CIS/EIS); A:(0|1)
'||': 'ORL', ## A=(A || x); F=undef/A (CIS/EIS); A:(0|1)
'==': 'EQ', ## A=(A == x); F=undef/A (CIS/EIS); A:(0|1)
'!=': 'NE', ## A=(A != x); F=undef/A (CIS/EIS); A:(0|1)
'>': 'GT', ## A=(A > x); F=undef/A (CIS/EIS); A:(0|1)
'>=': 'GE', ## A=(A >= x); F=undef/A (CIS/EIS); A:(0|1)
'<': 'LT', ## A=(A < x); F=undef/A (CIS/EIS); A:(0|1)
'<=': 'LE' } ## A=(A <= x); F=undef/A (CIS/EIS); A:(0|1)
PARAM_PATTERN = re.compile(r'(?:.*_)?(p[0-9])(?:_.*)?')
def __init__(self, log, c_sources, use_cis=True):
self.log = log ## PccLogger, log sink
self.c_sources = c_sources ## CSourceBundle, C sources to compile
self.use_cis = use_cis ## bool, True: use classic instruction set, else: extended instruction set
self.functions = {} ## dict(str func_name: Function function), user-defined and VM API functions
self.init_asm_buf = AsmBuffer() ## AsmBuffer, topmost output buffer
self.asm_out = self.init_asm_buf ## AsmBuffer, current output buffer
self.scope = collections.ChainMap() ## ChainMap, current scope with chained parents
self.context_function = None ## None or UserDefFunction, current function context
self.loop_tag_stack = [] ## list(), stack of loop AsmTag contexts
self.loop_continue_tag = None ## None or AsmTag, current tag to JMP to in case of a "continue" statement
self.loop_break_tag = None ## None or AsmTag, current tag to JMP to in case of a "break" statement
self.in_expression = False ## bool, True: currently evaluating an expression
if use_cis:
self.em_instrs = EmulatedInstrs() ## EmulatedInstrs, set of emulated instructions used
def compile(self, ast_root_node):
for node in ast_root_node:
try:
self.compile_statement(node)
except PccError as e:
self.log.error(e)
return self.log.error_count
## Private functions
def push_scope(self):
self.scope = self.scope.new_child()
def pop_scope(self):
self.scope = self.scope.parents
def push_loop_tags(self, begin_tag, end_tag):
self.loop_tag_stack.append((self.loop_continue_tag, self.loop_break_tag))
self.loop_continue_tag = begin_tag
self.loop_break_tag = end_tag
def pop_loop_tags(self):
self.loop_continue_tag, self.loop_break_tag = self.loop_tag_stack.pop()
def find_symbol(self, cname, filter=None):
symbol = self.scope.get(cname, None)
if symbol is not None and (filter is None or isinstance(symbol, filter)):
return symbol
return None
def bind_symbol(self, node, sym_obj):
if sym_obj.cname in self.scope.maps[0]:
raise PccError(node, f'redefinition of "{sym_obj.cname}"')
self.scope.maps[0][sym_obj.cname] = sym_obj
return sym_obj
def declare_enum(self, enum_decl):
enum_cursor = 0
for enum_node in enum_decl.values.enumerators:
value_node = enum_node.value
if value_node is None:
enum_value = str(enum_cursor)
enum_cursor += 1
else:
const_value = self.try_parse_constant(value_node)
if const_value is None:
raise PccError(value_node, 'unsupported enum syntax')
enum_value = const_value
enum_cursor = int(enum_value, 0) + 1
self.bind_symbol(enum_node, EnumSymbol(enum_node.name, enum_value))
def declare_variable(self, node, ctype, cname, asm_var=None):
return self.bind_symbol(node, VmVariableSymbol(ctype, cname, asm_var, node, self.context_function))
def declare_parameter(self, node, ctype, cname):
m = self.PARAM_PATTERN.fullmatch(cname)
if not m:
raise PccError(node, 'external variable names must contain one of "p0", "p1", ..., "p9"')
vm_param_name = m.groups(0)[0]
return self.bind_symbol(node, VmParameterSymbol(ctype, cname, vm_param_name))
def declare_function(self, node, is_vm_function=False):
## return previously bound symbol if exists
func_name = node.name
prototype = FunctionPrototype(node, is_vm_function)
func_sym = self.find_symbol(func_name, filter=FunctionSymbol)
if func_sym is not None:
if func_sym.function.prototype.matches(prototype):
return func_sym
else:
raise PccError(node, 'function prototype conflicts with previous declaration')
## find or create distinct Function object
if func_name in self.functions:
if not self.functions[func_name].prototype.matches(prototype):
raise PccError(node, 'function prototype conflicts with previous declaration')
elif is_vm_function:
self.functions[func_name] = VmApiFunction(node, prototype, self.use_cis)
else:
self.functions[func_name] = UserDefFunction(node, prototype)
## bind new symbol
return self.bind_symbol(node, FunctionSymbol(func_name, self.functions[func_name]))
def try_parse_constant(self, node):
result = None
if isinstance(node, c_ast.Constant) and node.type == 'int':
result = node.value
elif isinstance(node, c_ast.ID):
enum_sym = self.find_symbol(node.name, filter=EnumSymbol)
if enum_sym is not None:
result = enum_sym.const_value
elif isinstance(node, c_ast.UnaryOp) and node.op == '-':
if isinstance(node.expr, c_ast.Constant):
result = str(-int(node.expr.value, 0))
elif isinstance(node.expr, c_ast.ID):
enum_sym = self.find_symbol(node.expr.name, filter=EnumSymbol)
if enum_sym is not None:
result = str(-int(enum_sym.const_value, 0))
return result
def try_parse_term(self, node):
result = self.try_parse_constant(node)
if result is None and isinstance(node, c_ast.ID):
var_sym = self.find_symbol(node.name, filter=VariableSymbol)
if var_sym is None:
raise PccError(node, f'undeclared variable "{node.name}"')
result = var_sym.asm_repr()
return result
## Code-generating functions
def compile_expression(self, node):
node_term = self.try_parse_term(node)
if node_term is not None:
if self.use_cis:
self.asm_out('LDA', node_term) ## CIS: A := (node-expr), F := undef
else:
self.asm_out('LDAF', node_term) ## EIS: A := (node-expr), F := A
elif isinstance(node, (c_ast.UnaryOp, c_ast.BinaryOp, c_ast.Assignment, c_ast.FuncCall)):
prev_in_expression = self.in_expression
self.in_expression = True
try:
self.compile_statement(node) ## A := (node-expr); F := undef/A (CIS/EIS)
finally:
self.in_expression = prev_in_expression
else:
raise PccError(node, 'unsupported expression syntax')
def compile_assignment(self, dst_reg, rhs_node, assign_op='='):
rhs_term = self.try_parse_term(rhs_node)
if assign_op == '=': ## Simple assignment ("=")
if rhs_term is not None:
self.asm_out('LD', dst_reg, rhs_term) ## dst_reg := (rhs-term)
if self.in_expression:
if self.use_cis:
self.asm_out('LDA', dst_reg) ## CIS: A := dst_reg; F := undef
else:
self.asm_out('LDAF', dst_reg) ## EIS: A := dst_reg; F := A
else:
self.compile_expression(rhs_node) ## A := (rhs-expr); F := undef/A (CIS/EIS)
self.asm_out('STA', dst_reg) ## dst_reg := A
elif assign_op[:-1] in self.BINARY_OP_INSTR: ## Assignment operator ("+=", "/=", ...)
op_instr = self.BINARY_OP_INSTR[assign_op[:-1]]
if rhs_term is not None:
op_rhs = rhs_term
else:
self.compile_expression(rhs_node) ## A := (rhs-expr); F := undef/A (CIS/EIS)
self.asm_out('STA', SCR0) ## SCR0 := A
op_rhs = SCR0
self.asm_out('LDA', dst_reg) ## A := dest_reg
self.asm_out(op_instr, op_rhs) ## A := A <OP> op_rhs; F := A
self.asm_out('STA', dst_reg) ## dst_reg := A
else:
raise PccError(rhs_node, f'unsupported assignment operator "{assign_op}"')
def compile_asm_statement(self, node):
if node.args is None or not isinstance(node.args, c_ast.ExprList) or len(node.args.exprs) == 0:
return False
## parse arguments into instr_args[]
instr_args = []
is_1st_arg_str = False
for i_arg, arg_expr in enumerate(node.args.exprs):
arg_term = self.try_parse_term(arg_expr)
if arg_term is None and isinstance(arg_expr, c_ast.Constant) and arg_expr.type == 'string':
arg_term = bytes(arg_expr.value[1:-1], 'utf-8').decode('unicode_escape')
if i_arg == 0:
is_1st_arg_str = True
if arg_term is None:
raise PccError(arg_expr, 'asm() expects arguments to be variables, int or string constants')
instr_args.append(arg_term)
if not is_1st_arg_str:
raise PccError(node.args.exprs[0], 'asm() expects first argument to be a string constant')
instr = instr_args.pop(0).upper()
## replace user-defined static TAG labels with AsmTag objects
if AsmCmd.tag_instr_idx(instr) >= 0:
if len(instr_args) != 1:
raise PccError(node, f'{instr} expects a single tag label argument')
tag_label = instr_args[0]
static_tag = self.context_function.static_asm_tags.get(tag_label, None)
if static_tag is None:
static_tag = AsmTag()
self.context_function.static_asm_tags[tag_label] = static_tag
instr_args[0] = static_tag
## append raw assembler statement to current buffer
self.asm_out(instr, *instr_args)
return instr in ('RET', 'HALT')
def compile_statement(self, node):
ast_class_name = node.__class__.__name__
_compile_class_node = getattr(self, f'_compile_{ast_class_name}_node', None)
if not callable(_compile_class_node):
raise PccError(node, f'unsupported statement syntax (AST element {ast_class_name})')
return _compile_class_node(node)
def _compile_UnaryOp_node(self, node):
if node.op in ('++', '--', 'p++', 'p--'):
if not isinstance(node.expr, c_ast.ID):
raise PccError(node, 'increment operator expects variable')
reg_sym = self.find_symbol(node.expr.name, filter=VariableSymbol)
if reg_sym is None:
raise PccError(node.expr, f'undefined variable "{node.expr.name}"')
vm_reg = reg_sym.asm_repr()
if node.op == '++': ## Prefix increment "++X":
self.asm_out('INR', vm_reg) ## ++X, F := X
self.asm_out('LDA', vm_reg) ## A := X, F := A
elif node.op == '--': ## Prefix deccrement "--X":
self.asm_out('DCR', vm_reg) ## --X, F := X
self.asm_out('LDA', vm_reg) ## A := X, F := A
elif node.op == 'p++': ## Postfix increment "X++":
self.asm_out('LD', SCR0, vm_reg) ## SCR0 := X
self.asm_out('INR', vm_reg) ## ++X, F := X
if self.use_cis:
self.asm_out('LDA', SCR0) ## CIS: A := SCR0, F := undef
else:
self.asm_out('LDAF', SCR0) ## EIS: A := SCR0, F := A
elif node.op == 'p--': ## Postfix decrement "X--":
self.asm_out('LD', SCR0, vm_reg) ## SCR0 := X
self.asm_out('DCR', vm_reg) ## --X, F := X
if self.use_cis:
self.asm_out('LDA', SCR0) ## CIS: A := SCR0; F := undef
else:
self.asm_out('LDAF', SCR0) ## EIS: A := SCR0; F := A
elif node.op in self.UNARY_OP_INSTR:
self.compile_expression(node.expr) ## A := (expr); F := undef/A (CIS/EIS)
op_instr = self.UNARY_OP_INSTR[node.op]
if op_instr is not None:
if self.use_cis:
self.em_instrs.compile(self, op_instr) ## CIS: A := <OP> A; F := undef
else:
self.asm_out(op_instr) ## EIS: A := <OP> A; F := A
else:
raise PccError(node, f'unsupported unary operator "{node.op}"')
return False
def _compile_BinaryOp_node(self, node):
if node.op not in self.BINARY_OP_INSTR:
raise PccError(node, f'unsupported binary operator "{node.op}"')
op_instr = self.BINARY_OP_INSTR[node.op]
## compile left-hand side (lhs) into ACC
self.compile_expression(node.left) ## A := (lhs-expr); F := undef/A (CIS/EIS)
## compile right-hand side (rhs) and combine with lhs using <OP>
rhs_term = self.try_parse_term(node.right)
if rhs_term is not None:
if self.use_cis and self.em_instrs.is_emulated(op_instr):
self.asm_out('LD', SCR0, rhs_term)
self.em_instrs.compile(self, op_instr) ## CIS: A := A <OP> x; F := undef
else:
self.asm_out(op_instr, rhs_term) ## CIS/EIS: A := A <OP> x, F := A
else:
self.asm_out('PUSHA') ## save ACC (lhs) onto stack
self.compile_expression(node.right) ## A := (rhs-expr); F := undef/A (CIS/EIS)
self.asm_out('STA', SCR0) ## SCR0 := A
self.asm_out('POPA') ## restore lhs in ACC from stack
if self.use_cis and self.em_instrs.is_emulated(op_instr):
self.em_instrs.compile(self, op_instr) ## CIS: A := A <OP> SCR0; F := undef
else:
self.asm_out(op_instr, SCR0) ## CIS/EIS: A := A <OP> SCR0, F := A
return False
def _compile_Assignment_node(self, node):
lhs_sym = self.find_symbol(node.lvalue.name, filter=VariableSymbol)
if lhs_sym is None:
raise PccError(node.lvalue, f'undefined variable "{node.lvalue.name}"')
lhs_reg = lhs_sym.asm_repr()
self.compile_assignment(lhs_reg, node.rvalue, assign_op=node.op)
return False
def _compile_Compound_node(self, node):
returned = False
if node.block_items is not None:
self.push_scope()
try:
in_unreachable_code = False
for statement_node in node.block_items:
if in_unreachable_code:
self.log.warning(statement_node, 'unreachable code', self.context_function)
break
try:
s_returned = self.compile_statement(statement_node)
if s_returned:
returned = True
if s_returned or isinstance(statement_node, (c_ast.Continue, c_ast.Break)):
in_unreachable_code = True
except PccError as e:
self.log.error(e, context_function=self.context_function)
finally:
self.pop_scope()
return returned
def _compile_Return_node(self, node):
ret_val_expected = self.context_function.has_return
ret_val_given = node.expr is not None
if not ret_val_expected and ret_val_given:
self.log.warning(node, 'function does not return a value', self.context_function)
elif ret_val_expected and not ret_val_given:
self.log.warning(node, 'function should return a value', self.context_function)
elif ret_val_given:
self.compile_expression(node.expr) ## A := (expr); F := A
self.asm_out('RET')
return True
def _compile_Decl_node(self, node):
if len(node.align) != 0 or node.bitsize is not None or len(node.funcspec) != 0:
raise PccError(node, 'unsupported declaration syntax')
is_extern = False
if len(node.storage) > 0:
if len(node.storage) != 1 or node.storage[0] != 'extern':
raise PccError(node, f'unsupported storage qualifier "{" ".join(node.storage)}"')
is_extern = True
decl_type = node.type
if isinstance(decl_type, c_ast.TypeDecl):
if len(decl_type.quals) != 0:
raise PccError(node, f'unsupported type qualifier "{" ".join(decl_type.quals)}"')
if isinstance(decl_type.type, c_ast.IdentifierType):
if len(decl_type.type.names) == 1 and decl_type.type.names[0] in ('int', 'long'):
var_ctype = decl_type.type.names[0]
else:
raise PccError(node, f'unsupported variable type "{" ".join(decl_type.type.names)}"')
elif isinstance(decl_type.type, c_ast.Enum):
self.declare_enum(decl_type.type)
var_ctype = 'int'
else:
raise PccError(decl_type, 'unsupported variable type')
var_cname = decl_type.declname
if is_extern:
var_sym = self.declare_parameter(node, var_ctype, var_cname)
else:
var_sym = self.declare_variable(node, var_ctype, var_cname)
if node.init is not None:
self.compile_assignment(var_sym.asm_repr(), node.init)
elif isinstance(decl_type, c_ast.FuncDecl):
self.declare_function(node, is_vm_function=is_extern)
elif isinstance(decl_type, c_ast.Enum):
self.declare_enum(decl_type)
else:
raise PccError(node, 'unsupported declaration syntax')
return False
def _compile_FuncDef_node(self, node):