-
Notifications
You must be signed in to change notification settings - Fork 7
/
asfv1.py
1434 lines (1364 loc) · 53.2 KB
/
asfv1.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
#
# asfv1: Alternate FV-1 Assembler
# Copyright (C) 2017-2019 Nathan Fraser
#
# Python 2 compatibility
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
# Imports
import argparse
import sys
import shlex
import struct
# Constants
VERSION = '1.2.7'
PROGLEN = 128
DELAYSIZE = 32767
MAXERR = 10 # abort assembly if too many errors found
# Fixed point reals SN_D with one sign bit (S),
# N integer bits and D fractional bits:
#
# REF_... reference value at +1.0: 2**D
# MIN_... smallest real number: -2**(N+D)/2**D == -2**N
# MAX_... largest real number: (2**(N+D)-1)/REF
#
REF_S1_14 = 2.0**14 # 16384.0
MIN_S1_14 = -2.0**1 # -2.0
MAX_S1_14 = (2.0**(1+14)-1.0)/REF_S1_14 # 1.99993896484375
REF_S1_9 = 2.0**9 # 512.0
MIN_S1_9 = -2.0**1 # -2.0
MAX_S1_9 = (2.0**(1+9)-1.0)/REF_S1_9 # 1.998046875
REF_S_10 = 2.0**10 # 1024.0
MIN_S_10 = -2.0**0 # -1.0
MAX_S_10 = (2.0**(0+10)-1.0)/REF_S_10 # 0.9990234375
REF_S_15 = 2.0**15 # 32768.0
MIN_S_15 = -2.0**0 # -1.0
MAX_S_15 = (2.0**(0+15)-1.0)/REF_S_15 # 0.999969482421875
REF_S4_6 = 2.0**6 # 64.0
MIN_S4_6 = -2.0**4 # -16.0
MAX_S4_6 = (2.0**(4+6)-1.0)/REF_S4_6 # 15.984375
REF_S_23 = 2.0**23 # 8388608.0
MIN_S_23 = -2.0**0 # -1.0
MAX_S_23 = (2.0**(0+23)-1.0)/REF_S_23 # 0.9999998807907104
# Bit Masks
M1 = 0x01
M2 = 0x03
M5 = 0x1f
M6 = 0x3f
M8 = 0xff
M9 = 0x1ff
M11 = 0x7ff
M14 = 0x3fff
M15 = 0x7fff
M16 = 0xffff
M24 = 0xffffff
M27 = 0x7ffffff
M32 = 0xffffffff
def quiet(msg):
pass
def warning(msg):
print(msg, file=sys.stderr)
def error(msg):
print(msg, file=sys.stderr)
def bintoihex(buf, spos=0x0000, width=4):
"""Convert binary buffer to ihex and return as string."""
c = 0
olen = len(buf)
ret = ""
while(c < olen):
rem = olen-c
if rem > width:
rem = width
sum = rem
adr = c + spos
l = ':{0:02X}{1:04X}00'.format(rem,adr) # rem < 0x10
sum += ((adr>>8)&M8)+(adr&M8)
for j in range(0,rem):
nb = buf[c+j]
l += '{0:02X}'.format(nb)
sum = (sum + nb)&M8
l += '{0:02X}'.format((~sum+1)&M8)
ret += l + '\n'
c += rem
ret += ':00000001FF\n' # EOF
return ret
# Machine instruction table
op_tbl = {
# mnemonic: [opcode, (arglen,left shift), ...]
'RDA': [0b00000, (M15,5),(M11,21)],
'RMPA': [0b00001, (M11,21)],
'WRA': [0b00010, (M15,5),(M11,21)],
'WRAP': [0b00011, (M15,5),(M11,21)],
'RDAX': [0b00100, (M6,5),(M16,16)],
'RDFX': [0b00101, (M6,5),(M16,16)],
'LDAX': [0b00101, (M6,5)], # psuedo: RDFX REG,0
'WRAX': [0b00110, (M6,5),(M16,16)],
'WRHX': [0b00111, (M6,5),(M16,16)],
'WRLX': [0b01000, (M6,5),(M16,16)],
'MAXX': [0b01001, (M6,5),(M16,16)],
'ABSA': [0b01001, ], # pseudo: MAXX 0,0
'MULX': [0b01010, (M6,5)],
'LOG': [0b01011, (M16,16),(M11,5)],
'EXP': [0b01100, (M16,16),(M11,5)],
'SOF': [0b01101, (M16,16),(M11,5)],
'AND': [0b01110, (M24,8)],
'CLR': [0b01110, ], # pseudo: AND $0
'OR' : [0b01111, (M24,8)],
'XOR': [0b10000, (M24,8)],
'NOT': [0b10000, (M24,8)], # pseudo: XOR $ffffff
'SKP': [0b10001, (M5,27),(M6,21)], # note 1
'JMP': [0b10001, (M5,27),(M6,21)], # pseudo skp 0,...
'NOP': [0b10001, ], # pseudo: SKP 0,0 note 2
'WLDS': [0b10010, (M1,29),(M9,20),(M15,5)],
'WLDR': [0b10010, (M2,29),(M16,13),(M2,5)], # CHECK
'JAM': [0b10011, (M2,6)],
'CHO': [0b10100, (M2,30),(M2,21),(M6,24),(M16,5)], # CHECK
'RAW': [0b00000, (M32,0)], # direct data insertion
# Notes:
# 1. In SpinASM IDE , condition flags expand to shifted values,
# 2. NOP is not documented, but expands to SKP 0,0 in SpinASM
}
def op_gen(mcode):
"""Generate a machine instruction using the op gen table."""
gen = op_tbl[mcode[0]]
ret = gen[0] # opcode
nargs = len(gen)
i = 1
while i < nargs:
if i < len(mcode): # or assume they are same len
ret |= (mcode[i]&gen[i][0]) << gen[i][1]
i += 1
return ret
class fv1parse(object):
def __init__(self, source=None, clamp=True,
spinreals=False, wfunc=None, efunc=None):
self.program = bytearray(512)
self.doclamp = clamp
self.spinreals = spinreals
self.dowarn = wfunc
self.doerror = efunc
self.delaymem = 0
self.prevline = 0 # line number for last accepted symbol
self.sline = 0 # line number of current symbol
self.icnt = 0
self.sym = None
self.ecount = 0
self.source = source.split('\n')
self.linebuf = []
self.pl = [] # parse list
self.mem = {} # delay memory
self.jmptbl = { # jump table for skips
}
self.symtbl = { # symbol table
'SIN0_RATE': 0x00,
'SIN0_RANGE': 0x01,
'SIN1_RATE': 0x02,
'SIN1_RANGE': 0x03,
'RMP0_RATE': 0x04,
'RMP0_RANGE': 0x05,
'RMP1_RATE': 0x06,
'RMP1_RANGE': 0x07,
'POT0': 0x10,
'POT1': 0x11,
'POT2': 0x12,
'ADCL': 0x14,
'ADCR': 0x15,
'DACL': 0x16,
'DACR': 0x17,
'ADDR_PTR': 0x18,
'REG0': 0x20,
'REG1': 0x21,
'REG2': 0x22,
'REG3': 0x23,
'REG4': 0x24,
'REG5': 0x25,
'REG6': 0x26,
'REG7': 0x27,
'REG8': 0x28,
'REG9': 0x29,
'REG10': 0x2a,
'REG11': 0x2b,
'REG12': 0x2c,
'REG13': 0x2d,
'REG14': 0x2e,
'REG15': 0x2f,
'REG16': 0x30,
'REG17': 0x31,
'REG18': 0x32,
'REG19': 0x33,
'REG20': 0x34,
'REG21': 0x35,
'REG22': 0x36,
'REG23': 0x37,
'REG24': 0x38,
'REG25': 0x39,
'REG26': 0x3a,
'REG27': 0x3b,
'REG28': 0x3c,
'REG29': 0x3d,
'REG30': 0x3e,
'REG31': 0x3f,
'SIN0': 0x00,
'SIN1': 0x01,
'RMP0': 0x02,
'RMP1': 0x03,
'RDA': 0x00,
'SOF': 0x02,
'RDAL': 0x03,
'SIN': 0x00,
'COS': 0x01,
'REG': 0x02,
'COMPC': 0x04,
'COMPA': 0x08,
'RPTR2': 0x10,
'NA': 0x20,
'RUN': 0x10,
'ZRC': 0x08,
'ZRO': 0x04,
'GEZ': 0x02,
'NEG': 0x01,
}
def __mkopcodes__(self):
"""Convert the parse list into machine code for output."""
proglen = len(self.pl)
self.dowarn('info: Read {} instructions from input'.format(
proglen))
# pad free space with empty SKP instructions
icnt = proglen
while icnt < PROGLEN:
self.pl.append({'cmd':['SKP',0x00,0x00],
'addr':icnt,
'target':None})
icnt += 1
# convert program to machine code and prepare for output
oft = 0
for i in self.pl:
struct.pack_into('>I', self.program, oft, op_gen(i['cmd']))
oft += 4
def __register__(self, mnemonic=''):
"""Fetch a register definition."""
xtra = ''
if mnemonic:
xtra = ' for ' + mnemonic
reg = self.__expression__()
if int(reg) == reg:
reg = int(reg)
if reg < 0 or reg > 63:
self.parseerror('Register {0:#x} out of range'.format(reg)
+ xtra)
reg = 0
else:
self.parseerror('Invalid register {}'.format(reg)
+ xtra)
reg = 0
return reg
def __d_15__(self,mnemonic=''):
"""Fetch a 15 bit delay address, preferring integer interpretation"""
xtra = ''
if mnemonic:
xtra = ' for ' + mnemonic
oft = self.__expression__()
if oft < MIN_S_15 or oft > MAX_S_15:
oft = int(round(oft))
if oft < -0x8000 or oft > M15:
if self.doclamp:
if oft < -0x8000:
oft = -0x8000
elif oft > M15:
oft = M15
self.parsewarn('Address clamped to {0:#x}'.format(oft)
+ xtra)
else:
self.parseerror('Invalid address {0:#x}'.format(oft)
+ xtra)
oft = 0
else:
oft = int(round(oft * REF_S_15))
return oft
def __offset__(self, mnemonic=''):
"""Fetch a skip offset definition."""
xtra = ''
if mnemonic:
xtra = ' for ' + mnemonic
oft = self.__expression__()
if int(oft) == oft:
oft = int(oft)
if oft < 0 or oft > M6:
self.parseerror('Offset {} out of range'.format(oft)
+ xtra)
oft = 0
else:
self.parseerror('Invalid offset {}'.format(oft)
+ xtra)
oft = 0
return oft
def __condition__(self, mnemonic=''):
"""Fetch a skip condition code."""
xtra = ''
if mnemonic:
xtra = ' for ' + mnemonic
cond = self.__expression__()
if int(cond) == cond:
cond = int(cond)
if cond < 0 or cond > M5:
self.parseerror('Condition {0:#x} out of range'.format(
cond) + xtra)
cond = 0
else:
self.parseerror('Invalid condition {}'.format(cond) + xtra)
cond = 0
return cond
def __chotype__(self):
"""Fetch CHO type code."""
# this is not an operand - the symbol text is examined directly
chotype = self.sym['stxt']
self.__next__()
if chotype in ['RDA','SOF','RDAL']:
chotype = self.symtbl[chotype]
else:
self.parseerror('Invalid CHO type {}'.format(chotype))
chotype = 0
return chotype
def __choflags__(self, lfo=None):
"""Fetch CHO condition flags."""
flags = self.__expression__()
if int(flags) == flags:
flags = int(flags)
if flags < 0 or flags > M6:
self.parseerror('Invalid flags {0:#x} for CHO'.format(flags))
flags = 0
else:
self.parseerror('Invalid flags {} for CHO'.format(flags))
flags = 0
oflags = flags
if lfo&0x02: # RMP0/RMP1
flags = oflags & 0x3e
if oflags != flags:
self.parsewarn('RMP flags set to {0:#x} for CHO'.format(
flags))
else:
flags = oflags & 0x0f
if oflags != flags:
self.parsewarn('SIN flags set to {0:#x} for CHO'.format(
flags))
return flags
def __s1_14__(self, mnemonic=''):
"""Fetch a 16 bit real argument."""
xtra = ''
if mnemonic:
xtra = ' for ' + mnemonic
arg = self.__expression__()
if isinstance(arg, int):
if arg < 0 or arg > M16:
if self.doclamp:
if arg < 0:
arg = 0
elif arg > M16:
arg = M16
self.parsewarn('S1_14 arg clamped to {0:#x}'.format(arg)
+ xtra)
else:
self.parseerror('S1_14 arg {0:#x} out of range'.format(
arg) + xtra)
arg = 0
else:
if arg < MIN_S1_14 or arg > MAX_S1_14:
if self.doclamp:
if arg < MIN_S1_14:
arg = MIN_S1_14
elif arg > MAX_S1_14:
arg = MAX_S1_14
self.parsewarn('S1_14 arg clamped to {}'.format(arg)
+ xtra)
else:
self.parseerror('S1_14 arg {} out of range'.format(arg)
+ xtra)
arg = 0
arg = int(round(arg * REF_S1_14))
return arg
def __s_10__(self, mnemonic=''):
"""Fetch an 11 bit S_10 real argument."""
xtra = ''
if mnemonic:
xtra = ' for ' + mnemonic
arg = self.__expression__()
if isinstance(arg, int):
if arg < 0 or arg > M11:
if self.doclamp:
if arg < 0:
arg = 0
elif arg > M11:
arg = M11
self.parsewarn('S_10 arg clamped to {0:#x}'.format(
arg) + xtra)
else:
self.parseerror('S_10 arg {0:#x} out of range'.format(
arg) + xtra)
arg = 0
else:
if arg < MIN_S_10 or arg > MAX_S_10:
if self.doclamp:
if arg < MIN_S_10:
arg = MIN_S_10
elif arg > MAX_S_10:
arg = MAX_S_10
self.parsewarn('S_10 arg clamped to {}'.format(arg)
+ xtra)
else:
self.parseerror('S_10 arg {} out of range'.format(arg)
+ xtra)
arg = 0
arg = int(round(arg * REF_S_10))
return arg
def __s_15a__(self, mnemonic=''):
"""Fetch a 16 bit S_15 real address argument."""
xtra = ''
if mnemonic:
xtra = ' for ' + mnemonic
arg = self.__expression__()
if self.spinreals and arg == int(arg):
arg = int(arg)
if isinstance(arg, int):
if arg < 0 or arg > M16:
if self.doclamp:
if arg < 0:
arg = 0
elif arg > M16:
arg = M16
self.parsewarn('S_15 arg clamped to {0:#x}'.format(
arg) + xtra)
else:
self.parseerror('S_15 arg {0:#x} out of range'.format(
arg) + xtra)
arg = 0
else:
if arg < MIN_S_15 or arg > MAX_S_15:
if self.doclamp:
if arg < MIN_S_15:
arg = MIN_S_15
elif arg > MAX_S_15:
arg = MAX_S_15
self.parsewarn('S_15 arg clamped to {}'.format(arg)
+ xtra)
else:
self.parseerror('S_15 arg {} out of range'.format(arg)
+ xtra)
arg = 0
arg = int(round(arg * REF_S_15))
return arg
def __u_32__(self, mnemonic=''):
"""Fetch a raw 32 bit data string."""
xtra = ''
if mnemonic:
xtra = ' for ' + mnemonic
arg = self.__expression__()
if isinstance(arg, int):
if arg < 0 or arg > M32:
if self.doclamp:
if arg < 0:
arg = 0
elif arg > M32:
arg = M32
self.parsewarn('U_32 arg clamped to {0:#x}'.format(arg)
+ xtra)
else:
self.parseerror('U_32 arg {0:#x} out of range'.format(
arg) + xtra)
arg = 0
else:
self.parseerror('Invalid U_32 arg {}'.format(arg) + xtra)
arg = 0
return arg
def __s_23__(self, mnemonic=''):
"""Fetch a 24 bit S_23 real or mask argument."""
xtra = ''
if mnemonic:
xtra = ' for ' + mnemonic
arg = self.__expression__()
if isinstance(arg, int):
if arg < 0 or arg > M24:
if self.doclamp:
if arg < 0:
arg = 0
elif arg > M24:
arg = M24
self.parsewarn('S_23 arg clamped to {0:#x}'.format(
arg) + xtra)
else:
self.parseerror('S_23 arg {0:#x} out of range'.format(
arg) + xtra)
arg = 0
else:
if arg < MIN_S_23 or arg > MAX_S_23:
if self.doclamp:
if arg < MIN_S_23:
arg = MIN_S_23
elif arg > MAX_S_23:
arg = MAX_S_23
self.parsewarn('S_23 arg clamped to {}'.format(arg)
+ xtra)
else:
self.parseerror('S_23 arg {} out of range'.format(arg)
+ xtra)
arg = 0
arg = int(round(arg * REF_S_23))
return arg
def __s1_9__(self, mnemonic=''):
"""Fetch an 11 bit real argument."""
xtra = ''
if mnemonic:
xtra = ' for ' + mnemonic
arg = self.__expression__()
if isinstance(arg, int):
if arg < 0 or arg > M11:
if self.doclamp:
if arg < 0:
arg = 0
elif arg > M11:
arg = M11
self.parsewarn('S1_9 arg clamped to {0:#x}'.format(
arg) + xtra)
else:
self.parseerror('S1_9 arg {0:#x} out of range'.format(
arg) + xtra)
arg = 0
else:
if arg < MIN_S1_9 or arg > MAX_S1_9:
if self.doclamp:
if arg < MIN_S1_9:
arg = MIN_S1_9
elif arg > MAX_S1_9:
arg = MAX_S1_9
self.parsewarn('S1_9 arg clamped to {}'.format(arg)
+ xtra)
else:
self.parseerror('S1_9 arg {} out of range'.format(arg)
+ xtra)
arg = 0
arg = int(round(arg * REF_S1_9))
return arg
def __s4_6__(self, mnemonic=''):
"""Fetch an 11 bit S4_6 argument."""
xtra = ''
if mnemonic:
xtra = ' for ' + mnemonic
arg = self.__expression__()
if isinstance(arg, int):
if arg < 0 or arg > M11:
if self.doclamp:
if arg < 0:
arg = 0
elif arg > M11:
arg = M11
self.parsewarn('S4_6 arg clamped to {0:#x}'.format(
arg) + xtra)
else:
self.parseerror('S4_6 arg {0:#x} out of range'.format(
arg) + xtra)
arg = 0
else:
if arg < MIN_S4_6 or arg > MAX_S4_6:
if self.doclamp:
if arg < MIN_S4_6:
arg = MIN_S4_6
elif arg > MAX_S4_6:
arg = MAX_S4_6
self.parsewarn('S4_6 arg clamped to {}'.format(arg)
+ xtra)
else:
self.parseerror('S4_6 arg {} out of range'.format(arg)
+ xtra)
arg = 0
arg = int(round(arg * REF_S4_6))
return arg
def __lfo__(self, mnemonic=''):
"""Select an LFO."""
# there is some ambiguity here - but it is resolved in
# WLDS by clearing the MSB, and in WLDR by ORing with 0x2
xtra = ''
if mnemonic:
xtra = ' for ' + mnemonic
##
## or check for cos0/cos1 here in the case of CHO
##
lfo = self.__expression__()
if int(lfo) == lfo:
lfo = int(lfo)
if lfo < 0 or lfo > 3:
self.parseerror('Invalid LFO {0:#x}'.format(lfo) + xtra)
lfo = 0
else:
self.parseerror('Invalid LFO {}'.format(lfo) + xtra)
lfo = 0
return lfo
def __lfo_sinfreq__(self, mnemonic=''):
"""Fetch a sine LFO frequency value."""
xtra = ''
if mnemonic:
xtra = ' for ' + mnemonic
freq = self.__expression__()
if int(freq) == freq:
freq = int(freq)
if freq < 0 or freq > M9:
if self.doclamp:
if freq < 0:
freq = 0
elif freq > M9:
freq = M9
self.parsewarn('Frequency clamped to {0:#x}'.format(freq)
+ xtra)
else:
self.parseerror('Invalid frequency {0:#x}'.format(freq)
+ xtra)
freq = 0
else:
self.parseerror('Invalid frequency {}'.format(freq)
+ xtra)
freq = 0
return freq
def __lfo_rampfreq__(self, mnemonic=''):
"""Fetch a RMP LFO frequency value."""
xtra = ''
if mnemonic:
xtra = ' for ' + mnemonic
freq = self.__expression__()
if freq < -0.5 or freq > MAX_S_15: # not quite right
freq = int(round(freq))
if freq < -0x8000 or freq > M15:
if self.doclamp:
if freq < -0x8000:
freq = -0x8000
elif freq > M15:
freq = M15
self.parsewarn('Frequency clamped to {0:#x}'.format(freq)
+ xtra)
else:
self.parseerror('Invalid frequency {0:#x}'.format(freq)
+ xtra)
freq = 0
else:
freq = int(round(freq * REF_S_15))
return freq
def __lfo_rampamp__(self, mnemonic=''):
"""Fetch a RMP LFO amplitude value."""
xtra = ''
if mnemonic:
xtra = ' for ' + mnemonic
amp = self.__expression__()
rampamps = {4096:0, 2048:1, 1024:2, 512:3, 0:0, 1:1, 2:2, 3:3}
if int(amp) == amp:
amp = int(amp)
if amp in rampamps:
amp = rampamps[amp]
else:
self.parseerror('Invalid amplitude {}'.format(amp)
+ xtra)
amp = 0
else:
self.parseerror('Invalid amplitude {}'.format(amp)
+ xtra)
amp = 0
return amp
def __next__(self):
"""Fetch next symbol."""
# Scanner uses shlex to break up the input, then reassembles
# tokens into one of:
#
# EOF : end of input marker
# MNEMONIC : instruction mnemonic text
# ASSEMBLER : assembler directive 'EQU' or 'MEM'
# OPERATOR : expression operator | ^ & << >> + - * // / ~ + - **
# INTEGER : integer numeric literal
# FLOAT : real numeric literal
# TARGET : target address in assembled program
# LABEL : text label
# ARGSEP : operand delimiting character ,
#
# comments are stripped by shlex.
self.sym = None
self.prevline = self.sline # line of last fetched symbol
while self.sym is None:
if len(self.linebuf) == 0: # nothing in line buf yet
if len(self.source) > 0: # still some lines in source
self.sline += 1
llex = shlex.shlex(self.source.pop(0))
llex.commenters = ';'
self.linebuf = [t for t in llex]
else:
self.sym = {'type': 'EOF', 'txt':None,
'stxt':None, 'val':None}
if len(self.linebuf) > 0:
stxt = self.linebuf[0].upper()
if stxt in op_tbl: # MNEMONIC
self.sym = {'type': 'MNEMONIC',
'txt': self.linebuf.pop(0),
'stxt': stxt,
'val': None}
elif stxt in ['EQU', 'MEM']:
self.sym = {'type': 'ASSEMBLER',
'txt': self.linebuf.pop(0),
'stxt': stxt,
'val': None}
elif stxt in ['<','>','*','/']:
optxt = self.linebuf.pop(0)
if len(self.linebuf) > 0:
if self.linebuf[0] == optxt: # **, //, <<, >>
optxt += self.linebuf.pop(0)
if optxt in ['<','>']:
self.scanerror('Invalid operator {}'.format(optxt))
optxt += optxt
self.sym = {'type': 'OPERATOR',
'txt': optxt,
'stxt': optxt,
'val': None}
elif stxt in ['|','^','&','+','-','~','!','(',')','INT']:
self.sym = {'type': 'OPERATOR',
'txt': self.linebuf.pop(0),
'stxt': stxt,
'val': None}
elif stxt[0] in ['%', '$']:
# SpinASM style integers
pref = self.linebuf.pop(0)
base = 2
if pref == '$':
base = 16
if len(self.linebuf) > 0:
ht = self.linebuf.pop(0)
ival = 0
try:
ival = int(ht.replace('_',''),base)
except:
self.scanerror('Invalid integer literal {}'.format(
pref+ht))
self.sym = {'type': 'INTEGER',
'txt': pref+ht,
'stxt': pref+ht,
'val': ival}
else:
self.scanerror('End of line scanning for integer')
self.sym = {'type': 'INTEGER',
'txt': pref,
'stxt': pref,
'val': 0}
elif stxt[0].isdigit(): # INTEGER or FLOAT
intpart = self.linebuf.pop(0).lower()
ival = 0.0
if len(self.linebuf) > 0 and self.linebuf[0] == '.':
self.linebuf.pop(0)
if len(self.linebuf) > 0:
frac = self.linebuf.pop(0)
if frac.endswith('e') and len(self.linebuf) > 0:
epart = self.linebuf.pop(0)
if epart in ['+','-'] and len(self.linebuf) > 0:
epart += self.linebuf.pop(0)
frac = frac+epart
try:
ival = float(intpart+'.'+frac)
except:
self.scanerror(
'Invalid numeric literal {}'.format(
intpart+'.'+frac))
self.sym = {'type': 'FLOAT',
'txt': intpart+'.'+frac,
'stxt': intpart+'.'+frac,
'val': ival}
else:
self.scanerror('Invalid numeric literal')
self.sym = {'type': 'FLOAT',
'txt': intpart+'.0',
'stxt': intpart+'.0',
'val': ival}
elif self.spinreals and intpart in ['2', '1']:
ival = float(intpart)
self.sym = {'type': 'FLOAT',
'stxt': intpart+'.0',
'txt': intpart,
'val': ival}
else: # assume integer
ival = 0
base = 10
if intpart.startswith('0x'):
base = 16
elif intpart.startswith('0b'):
base = 2
try:
ival = int(intpart, base)
except:
self.scanerror('Invalid integer literal {}'.format(
intpart))
self.sym = {'type': 'INTEGER',
'txt': intpart,
'stxt': intpart,
'val': ival}
elif stxt[0].isalpha(): # TARGET or LABEL
lbl = self.linebuf.pop(0)
if len(self.linebuf) > 0 and self.linebuf[0] == ':':
self.sym = {'type': 'TARGET',
'txt': lbl,
'stxt': stxt,
'val': None}
self.linebuf.pop(0)
else:
mod = ''
if len(self.linebuf) > 0 and self.linebuf[0] in [
'^','#']:
# is the label already defined as MEM?
if stxt+self.linebuf[0] in self.symtbl:
mod = self.linebuf.pop(0)
# else the modifier is ignored
self.sym = {'type': 'LABEL',
'txt': lbl+mod,
'stxt': stxt+mod,
'val': None}
elif stxt == ',': # ARGSEP
self.sym = {'type': 'ARGSEP',
'txt': self.linebuf.pop(0),
'stxt': stxt,
'val': None}
elif self.linebuf[0] == '\ufeff':
self.linebuf.pop(0) # ignore BOM
else:
self.scanerror('Unrecognised input {}'.format(
self.linebuf.pop(0)))
def scanerror(self, msg):
"""Emit scan error."""
self.doerror('scan error: ' + msg + ' on line {}'.format(self.sline))
self.ecount += 1
if self.ecount > MAXERR:
self.doerror('too many errors, aborting.')
sys.exit(-1)
def parsewarn(self, msg, line=None):
"""Emit parse warning."""
if line is None:
line = self.prevline
self.dowarn('warning: {} on line {}'.format(msg, line))
def parseerror(self, msg, line=None):
"""Emit parse error."""
if line is None:
line = self.prevline
self.doerror('parse error: {} on line {}'.format(msg, line))
self.ecount += 1
if self.ecount > MAXERR:
self.doerror('too many errors, aborting.')
sys.exit(-2)
def __accept__(self,stype,message=None):
"""Accept the next symbol if type matches stype."""
if self.sym['type'] == stype:
self.__next__()
else:
if message is not None:
self.parseerror(message)
else:
self.parseerror('Expected {} but saw {} {}'.format(
stype, self.sym['type'], self.sym['txt']),
self.sline)
def __instruction__(self):
"""Parse an instruction."""
mnemonic = self.sym['stxt']
opmsg = 'Missing required operand for '+mnemonic
self.__accept__('MNEMONIC')
if self.icnt >= PROGLEN:
self.parseerror('Max program exceeded by {}'.format(mnemonic))
if mnemonic in ['AND', 'OR', 'XOR', ]:
mask = self.__s_23__(mnemonic)
self.pl.append({'cmd':[mnemonic, mask],'addr':self.icnt})
self.icnt += 1
elif mnemonic in ['SOF', 'EXP', 'LOG', ]:
mult = self.__s1_14__(mnemonic)
self.__accept__('ARGSEP',opmsg)
oft = self.__s_10__(mnemonic)
self.pl.append({'cmd':[mnemonic, mult, oft], 'addr':self.icnt})
self.icnt += 1
elif mnemonic in ['RDAX', 'WRAX', 'MAXX', 'RDFX', 'WRLX', 'WRHX',]:
reg = self.__register__(mnemonic)
self.__accept__('ARGSEP',opmsg)
mult = self.__s1_14__(mnemonic)
self.pl.append({'cmd':[mnemonic, reg, mult], 'addr':self.icnt})
self.icnt += 1
elif mnemonic in ['MULX', ]:
reg = self.__register__(mnemonic)
self.pl.append({'cmd':[mnemonic, reg], 'addr':self.icnt})
self.icnt += 1
elif mnemonic in ['SKP','JMP']:
condition = 0
if mnemonic == 'SKP':
condition = self.__condition__(mnemonic)
self.__accept__('ARGSEP',opmsg)
target = None
offset = 0x00
sourceline = self.sline
if self.sym['type'] in ['LABEL','TARGET']:
target = self.sym['stxt']
self.__next__()
else:
offset = self.__offset__(mnemonic)
self.pl.append({'cmd':['SKP', condition, offset],
'target':target,
'addr':self.icnt,
'line':sourceline})
self.icnt += 1
elif mnemonic in ['RDA', 'WRA', 'WRAP',] :
addr = self.__d_15__(mnemonic)
self.__accept__('ARGSEP',opmsg)
mult = self.__s1_9__(mnemonic)
self.pl.append({'cmd':[mnemonic, addr, mult], 'addr':self.icnt})
self.icnt += 1
elif mnemonic == 'RMPA':
mult = self.__s1_9__(mnemonic)
self.pl.append({'cmd':[mnemonic, mult], 'addr':self.icnt})
self.icnt += 1
elif mnemonic == 'WLDS':
lfo = self.__lfo__(mnemonic)&0x01
self.__accept__('ARGSEP',opmsg)
freq = self.__lfo_sinfreq__(mnemonic)
self.__accept__('ARGSEP',opmsg)
amp = self.__d_15__(mnemonic)
self.pl.append({'cmd':[mnemonic, lfo, freq, amp],
'addr':self.icnt})
self.icnt += 1
elif mnemonic == 'WLDR':
lfo = self.__lfo__()|0x02
self.__accept__('ARGSEP',opmsg)
freq = self.__lfo_rampfreq__(mnemonic)
self.__accept__('ARGSEP',opmsg)
amp = self.__lfo_rampamp__(mnemonic)
self.pl.append({'cmd':[mnemonic, lfo, freq, amp],
'addr':self.icnt})
self.icnt += 1
elif mnemonic == 'CHO':
chotype = self.__chotype__()
self.__accept__('ARGSEP',opmsg)
lfo = self.__lfo__(mnemonic)
flags = 0b000010
arg = 0x00
if chotype == 0x00: # cho rda,lfo,flags,address
self.__accept__('ARGSEP',opmsg)
flags = self.__choflags__(lfo)
self.__accept__('ARGSEP',opmsg)
arg = self.__s_15a__(mnemonic)
elif chotype == 0x02: # cho sof,lfo,flags,offset
self.__accept__('ARGSEP',opmsg)
flags = self.__choflags__(lfo)
self.__accept__('ARGSEP',opmsg)
arg = self.__s_15a__(mnemonic)
elif chotype == 0x3: # cho rdal,lfo[,flags]
if self.sym['type'] == 'ARGSEP':
self.__accept__('ARGSEP')
flags = self.__choflags__(lfo)
self.pl.append({'cmd':['CHO', chotype, lfo, flags, arg],
'addr':self.icnt})
self.icnt += 1
elif mnemonic == 'JAM':
lfo = self.__lfo__(mnemonic)|0x02
self.pl.append({'cmd':[mnemonic, lfo], 'addr':self.icnt})
self.icnt += 1
elif mnemonic == 'CLR':