-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathxga99.py
executable file
·2101 lines (1884 loc) · 80.2 KB
/
xga99.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
# xga99: A GPL cross-assembler
#
# Copyright (c) 2015-2024 Ralph Benzinger <r@0x01.de>
#
# This program is part of the TI 99 Cross-Development Tools (xdt99).
#
# xdt99 is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
import sys
import os.path
import math
import re
import argparse
import zipfile
from xcommon import CommandProcessor, RFile, Util, Warnings, Console
VERSION = '3.6.5'
CONFIG = 'XGA99_CONFIG'
# Error handling
class AsmError(Exception):
pass
# Addresses
class Address:
"""absolute GROM address"""
def __init__(self, addr, local=False):
if local:
self.addr = addr & 0x1fff # address within GROM, e.g., BR/BS
self.size = 1
else:
self.addr = addr # global 16-bit address, e.g., B
self.size = 2
self.local = local
def __eq__(self, other):
return (isinstance(other, Address) and
self.addr == other.addr and
self.local == other.local)
def __ne__(self, other):
return not self == other
def hex(self):
"""return address as two-address tuple"""
return '{:02X}'.format(self.addr >> 8), '{:02X}'.format(self.addr & 0xff)
@staticmethod
def val(n):
"""dereference address"""
return n.addr if isinstance(n, Address) else n
class Local:
"""local label reference"""
def __init__(self, name, distance):
self.name = name
self.distance = distance
# Opcodes and Directives
class Opcodes:
op_imm = lambda parser, x: (parser.expression(x[0]),)
op_immb = lambda parser, x: (parser.byte_expression(x[0]),)
op_immb_gs = lambda parser, x: (parser.byte_expression(x[0]),
parser.gaddress(x[1], is_gs=True))
op_opt_255 = lambda parser, x: (parser.byte_expression(x[0]) if x else 255,)
op_gd = lambda parser, x: (parser.gaddress(x[0], is_gs=False),)
op_gs_gd = lambda parser, x: (parser.gaddress(x[0], is_gs=True),
parser.gaddress(x[1], is_gs=False))
op_gs_dgd = lambda parser, x: (parser.gaddress(x[0], is_gs=True, is_d=True),
parser.gaddress(x[1], is_gs=False))
op_lab = lambda parser, x: (parser.label(x[0]),)
op_move = lambda parser, x: parser.move(x)
opcodes = {
# 4.1 compare and test instructions
'H': (0x09, 5, None),
'GT': (0x0a, 5, None),
'CARRY': (0x0c, 5, None),
'OVF': (0x0d, 5, None),
'CEQ': (0xd4, 1, op_gs_gd),
'DCEQ': (0xd5, 1, op_gs_dgd),
'CH': (0xc4, 1, op_gs_gd),
'DCH': (0xc5, 1, op_gs_dgd),
'CHE': (0xc8, 1, op_gs_gd),
'DCHE': (0xc9, 1, op_gs_dgd),
'CGT': (0xcc, 1, op_gs_gd),
'DCGT': (0xcd, 1, op_gs_dgd),
'CGE': (0xd0, 1, op_gs_gd),
'DCGE': (0xd1, 1, op_gs_dgd),
'CLOG': (0xd8, 1, op_gs_gd),
'DCLOG': (0xd9, 1, op_gs_dgd),
'CZ': (0x8e, 6, op_gd),
'DCZ': (0x8f, 6, op_gd),
# 4.2 program control instructions
'BS': (0x60, 4, op_lab),
'BR': (0x40, 4, op_lab),
'B': (0x05, 3, op_lab),
'CASE': (0x8a, 6, op_gd),
'DCASE': (0x8b, 6, op_gd),
'CALL': (0x06, 3, op_lab),
'FETCH': (0x88, 6, op_gd),
'RTN': (0x00, 5, None),
'RTNC': (0x01, 5, None),
# 4.4 arithmetic and logical instructions
'ADD': (0xa0, 1, op_gs_gd),
'DADD': (0xa1, 1, op_gs_dgd),
'SUB': (0xa4, 1, op_gs_gd),
'DSUB': (0xa5, 1, op_gs_dgd),
'MUL': (0xa8, 1, op_gs_gd),
'DMUL': (0xa9, 1, op_gs_dgd),
'DIV': (0xac, 1, op_gs_gd),
'DDIV': (0xad, 1, op_gs_dgd),
'INC': (0x90, 6, op_gd),
'DINC': (0x91, 6, op_gd),
'INCT': (0x94, 6, op_gd),
'DINCT': (0x95, 6, op_gd),
'DEC': (0x92, 6, op_gd),
'DDEC': (0x93, 6, op_gd),
'DECT': (0x96, 6, op_gd),
'DDECT': (0x97, 6, op_gd),
'ABS': (0x80, 6, op_gd),
'DABS': (0x81, 6, op_gd),
'NEG': (0x82, 6, op_gd),
'DNEG': (0x83, 6, op_gd),
'INV': (0x84, 6, op_gd),
'DINV': (0x85, 6, op_gd),
'AND': (0xb0, 1, op_gs_gd),
'DAND': (0xb1, 1, op_gs_dgd),
'OR': (0xb4, 1, op_gs_gd),
'DOR': (0xb5, 1, op_gs_dgd),
'XOR': (0xb8, 1, op_gs_gd),
'DXOR': (0xb9, 1, op_gs_dgd),
'CLR': (0x86, 6, op_gd),
'DCLR': (0x87, 6, op_gd),
'ST': (0xbc, 1, op_gs_gd),
'DST': (0xbd, 1, op_gs_dgd),
'EX': (0xc0, 1, op_gs_gd),
'DEX': (0xc1, 1, op_gs_dgd),
'PUSH': (0x8c, 6, op_gd),
'MOVE': (0x20, 9, op_move),
'SLL': (0xe0, 1, op_gs_gd), # opGdGs in TI Guide ff.
'DSLL': (0xe1, 1, op_gs_dgd),
'SRA': (0xdc, 1, op_gs_gd),
'DSRA': (0xdd, 1, op_gs_dgd),
'SRL': (0xe4, 1, op_gs_gd),
'DSRL': (0xe5, 1, op_gs_dgd),
'SRC': (0xe8, 1, op_gs_gd),
'DSRC': (0xe9, 1, op_gs_dgd),
# 4.5 graphics and miscellaneous instructions
'COINC': (0xed, 1, op_gs_dgd),
'BACK': (0x04, 2, op_immb),
'ALL': (0x07, 2, op_immb),
'RAND': (0x02, 2, op_opt_255),
'SCAN': (0x03, 5, None),
'XML': (0x0f, 2, op_immb),
'EXIT': (0x0b, 5, None),
'I/O': (0xf6, 8, op_immb_gs), # opGsImm
# BASIC
'PARSE': (0x0e, 2, op_immb),
'CONT': (0x10, 5, None),
'EXEC': (0x11, 5, None),
'RTNB': (0x12, 5, None),
# undocumented
'SWGR': (0xf8, 1, op_gs_gd),
'DSWGR': (0xf9, 1, op_gs_dgd),
'RTGR': (0x13, 5, None)
# end of opcodes
}
pseudos = {
# 4.3 bit manipulation and pseudo instruction
'RB': ('AND', ['2**($1)^>FFFF', '$2']),
'SB': ('OR', ['2**($1)', '$2']),
'TBR': ('CLOG', ['2**($1)', '$2']),
'HOME': ('DCLR', ['@YPT']),
'POP': ('ST', ['*STATUS', '$1'])
}
op_text = lambda parser, x: parser.fmttext(x)
op_char = lambda parser, x: (parser.fmtcount(x[0]),
parser.expression(x[1]))
op_hstr = lambda parser, x: (parser.fmtcount(x[0], max_count=27),
parser.gaddress(x[1], is_gs=True, plain_only=True))
op_incr = lambda parser, x: (parser.fmtcount(x[0]),)
op_value = lambda parser, x: (1, parser.expression(x[0]))
op_bias = lambda parser, x: parser.fmtbias(x)
fmt_codes = {
'HTEXT': (0x00, op_text),
'VTEXT': (0x20, op_text),
'HCHAR': (0x40, op_char),
'VCHAR': (0x60, op_char),
'COL+': (0x80, op_incr),
'ROW+': (0xa0, op_incr),
'HSTR': (0xe0, op_hstr),
# 'FOR': (0xc0, op_value), # -> directive
# 'FEND': (0xfb, None), # -> directive
'BIAS': (0xfc, op_bias),
'ROW': (0xfe, op_value),
'COL': (0xff, op_value)
}
@staticmethod
def process(asm, label, mnemonic, operands):
"""get assembly code for mnemonic"""
asm.process_label(label)
if mnemonic in Opcodes.pseudos:
mnemonic, substs = Opcodes.pseudos[mnemonic]
operands = [re.sub(r'\$(\d+)',
lambda m: operands[int(m.group(1)) - 1], subst)
for subst in substs]
if asm.parser.fmt_mode:
try:
opcode, parse = Opcodes.fmt_codes[mnemonic]
args = parse(asm.parser, operands) if parse else ()
except (KeyError, ValueError, IndexError):
raise AsmError('Syntax error in FMT mode')
Opcodes.generate(asm, opcode, 7, args)
else:
try:
opcode, fmt, parse = Opcodes.opcodes[mnemonic]
args = parse(asm.parser, operands) if parse else ()
except (KeyError, ValueError, IndexError):
raise AsmError('Syntax error')
Opcodes.generate(asm, opcode, fmt, args)
@staticmethod
def generate(asm, opcode, fmt, args):
"""generate byte code"""
if fmt == 1:
assert isinstance(args[0], Operand)
s = 1 if args[0].immediate else 0
asm.emit(opcode | s << 1, args[1], args[0])
elif fmt == 2:
asm.emit(opcode, args[0])
elif fmt == 3:
asm.emit(opcode, Address(args[0]))
elif fmt == 4:
asm.emit(opcode, Address(args[0], local=True))
elif fmt == 5:
asm.emit(opcode)
elif fmt == 6:
asm.emit(opcode, args[0])
elif fmt == 7:
oo = args[0] - 1 if len(args) > 0 else 0
asm.emit(opcode | oo, *args[1:])
elif fmt == 8:
asm.emit(opcode, args[1], args[0] & 0xff)
elif fmt == 9:
oo, ln, gd, gs = args
asm.emit(opcode | oo, ln, gd, gs)
else:
raise AsmError(f'Unsupported opcode format {fmt}')
class Directives:
@staticmethod
def EQU(asm, label, ops):
value = asm.parser.expression(ops[0])
asm.symbols.add_symbol(label, value)
@staticmethod
def DATA(asm, label, ops):
asm.process_label(label, tracked=True)
asm.emit(*[Address(asm.parser.expression(op)) for op in ops])
@staticmethod
def BYTE(asm, label, ops):
asm.process_label(label, tracked=True)
asm.emit(*[asm.parser.expression(op) & 0xff for op in ops])
@staticmethod
def TEXT(asm, label, ops):
asm.process_label(label, tracked=True)
for op in ops:
text = asm.parser.text(op)
asm.emit(*[ord(c) for c in text])
@staticmethod
def STRI(asm, label, ops):
asm.process_label(label, tracked=True)
text = ''.join(asm.parser.text(op) for op in ops)
asm.emit(len(text), *[ord(c) for c in text])
@staticmethod
def FLOAT(asm, label, ops):
asm.process_label(label, tracked=True)
for op in ops:
bytes_ = asm.parser.radix100(op)
asm.emit(*bytes_)
@staticmethod
def BSS(asm, label, ops):
asm.process_label(label, tracked=True)
size = asm.parser.expression(ops[0])
asm.emit(*[0x00 for _ in range(size)])
@staticmethod
def GROM(asm, label, ops):
value = asm.parser.value(ops[0])
grom = (value << 13) if value < 8 else value & 0xe000
asm.org(grom, 0x0000)
asm.process_label(label)
@staticmethod
def AORG(asm, label, ops):
offset = asm.parser.value(ops[0])
if not 0 <= offset < 0x2000:
raise AsmError(f'AORG offset {offset:04X} out of range')
asm.org(asm.grom, offset)
asm.process_label(label)
@staticmethod
def TITLE(asm, label, ops):
asm.process_label(label)
text = asm.parser.text(ops[0])
asm.program.title = text[:12]
@staticmethod
def FMT(asm, label, ops):
asm.process_label(label)
asm.parser.fmt_mode = True
asm.emit(0x08)
@staticmethod
def FOR(asm, label, ops):
asm.process_label(label)
asm.parser.for_loops.append(Address(asm.symbols.LC + 1))
count = asm.parser.expression(ops[0])
asm.emit(0xC0 + count - 1)
@staticmethod
def FEND(asm, label, ops):
asm.process_label(label)
if asm.parser.for_loops:
addr = asm.parser.for_loops.pop()
if ops:
addr = Address(asm.parser.label(ops[0]))
asm.emit(0xFB, addr)
elif asm.parser.fmt_mode:
asm.emit(0xFB)
asm.parser.fmt_mode = False
else:
raise AsmError('Syntax error: unexpected FEND')
@staticmethod
def COPY(asm, label, ops):
asm.process_label(label)
filename = asm.parser.get_filename(ops[0])
asm.parser.open(filename=filename)
@staticmethod
def BCOPY(asm, label, ops):
"""extension: include binary file as BYTE stream"""
asm.process_label(label)
filename = asm.parser.get_filename(ops[0])
path = asm.parser.find(filename) # might throw exception
try:
with open(path, 'rb') as f:
bs = f.read()
asm.emit(*bs)
except IOError as e:
raise AsmError(e)
@staticmethod
def END(asm, label, ops):
asm.process_label(label)
if ops:
asm.program.entry = asm.symbols.get_symbol(ops[0], required=True)
asm.parser.stop()
ignores = [
'', 'PAGE', 'LIST', 'UNL', 'LISTM', 'UNLM'
]
@staticmethod
def process(asm, label, mnemonic, operands):
"""process directives"""
if mnemonic in Directives.ignores:
asm.process_label(label)
return True
try:
fn = getattr(Directives, mnemonic)
except AttributeError:
return False
try:
fn(asm, label, operands)
except (IndexError, ValueError):
raise AsmError('Syntax error')
return True
# Symbol table
class Symbols:
"""symbol table and line counter"""
def __init__(self, definitions=None, ryte_symbols=False):
self.symbols = {} # name: (value, used)
self.symbol_def_location = {} # symbol definition location (lino, filename)
self.updated = False # has at least one value changed?
self.pass_no = 0
self.LC = 0
self.lidx = 0
self.locations = [] # listing of (lidx, name), must not be deleted between passes
self.definitions = {
'MAXMEM': 0x8370, # CPU RAM
'DATSTK': 0x8372,
'SUBSTK': 0x8373,
'KEYBRD': 0x8374,
'KEY': 0x8375,
'JOYY': 0x8376,
'JOYX': 0x8377,
'RANDOM': 0x8378,
'TIMER': 0x8379,
'MOTION': 0x837a,
'VDPSTT': 0x837b,
'STATUS': 0x837c,
'CB': 0x837d,
'YPT': 0x837e,
'XPT': 0x837f,
'FAC': 0x834a, # floating point arithmetic
'ARG': 0x835c,
'SGN': 0x8375,
'EXP': 0x8376,
'VSPTR': 0x836e,
'FPERAD': 0x836c,
'ERCODE': 0x8354, # RAG assembler
'VPAB': 0x8356,
'VSTACK': 0x836e
}
self.ryte_data_defs = {
'ACCTON': 0x0034,
'ATN': 0x0032,
'BADTON': 0x0036,
'BITREV': 0x003B,
'CFI': 0x0012,
'CNS': 0x0014,
'COS': 0x002c,
'CSN': 0x0010,
'DIVZER': 0x0001,
'ERRIOV': 0x0003,
'ERRLOG': 0x0006,
'ERRNIP': 0x0005,
'ERRSNN': 0x0002,
'ERRSQR': 0x0004,
'EXPF': 0x0028,
'FADD': 0x0006,
'FCOMP': 0x000a,
'FDIV': 0x0009,
'FMUL': 0x0008,
'FSUB': 0x0007,
'GETSPACE': 0x0038,
'INT': 0x0022,
'LINK': 0x0010,
'LOCASE': 0x0018,
'LOG': 0x002a,
'MEMSIZ': 0x8370,
'NAMLNK': 0x003d,
'PAD': 0x8300,
'PWR': 0x0024,
'RETURN': 0x0012,
'SADD': 0x000b,
'SCOMP': 0x000f,
'SDIV': 0x000e,
'SIN': 0x002e,
'SMUL': 0x000d,
'SOUND': 0x8400,
'SQR': 0x0026,
'SSUB': 0x000c,
'STCASE': 0x0016,
'TAN': 0x0030,
'TRIGER': 0x0007,
'UPCASE': 0x004a,
'WRNOV': 0x0001
}
if definitions:
self.add_env(definitions)
if ryte_symbols:
self.definitions.update(self.ryte_data_defs)
def reset(self):
self.updated = False
@staticmethod
def valid(name):
"""is name a valid symbol name?"""
return (name[:1].isalpha() or name[0] == '_') and not re.search(r'[-+*/&|^~()#"\']', name)
def add_symbol(self, name, value, tracked=False, check=True, lino=None, filename=None):
"""add symbol to symbol table or update existing symbol"""
curr_value, unused = self.symbols.get(name, (None, False))
if self.pass_no == 0:
if check and not Symbols.valid(name):
raise AsmError(f'Invalid symbol name: {name}')
if curr_value is not None:
raise AsmError(f'Multiple symbols: {name}')
self.symbols[name] = value, tracked or None
self.symbol_def_location[name] = None if lino is None else (lino, filename)
elif curr_value != value:
self.symbols[name] = value, unused
self.updated = True
return name
def add_label(self, label, tracked=False, check=True, lino=None, filename=None):
"""add label, in every pass to update its LC"""
name = self.add_symbol(label, Address(self.LC), tracked=tracked, check=check, lino=lino, filename=filename)
if (self.lidx, name) not in self.locations:
self.locations.append((self.lidx, name))
def add_local_label(self, label):
"""add local label, in every pass to update its LC"""
self.add_label(label + '$' + str(self.lidx), check=False)
def add_env(self, definitions):
"""add external symbol definitions (-D)"""
for def_ in definitions:
try:
name, value_str = def_.split('=')
value = Parser.external(value_str)
except (ValueError, IndexError):
name, value = def_, 1
self.definitions[name.upper()] = value
def get_symbol(self, name, required=False, for_pass_0=False, rc_pass_0=0):
if self.pass_no == 0 and not for_pass_0: # required in pass 0
return rc_pass_0
try:
value, unused = self.symbols[name]
if unused:
self.symbols[name] = value, False
except KeyError:
value = self.definitions.get(name)
if required and value is None:
raise AsmError(f'Unknown symbol: {name}')
return value
def get_local(self, name, distance):
if self.pass_no == 0:
return 0
targets = [(loc, sym) for (loc, sym) in self.locations if sym[:len(name) + 1] == name + '$']
try:
i, lidx = next((j, l) for j, (l, n) in enumerate(targets) if l >= self.lidx)
if distance > 0 and lidx > self.lidx:
distance -= 1 # i points to +! unless lidx == self.lidx
except StopIteration:
i = len(targets) # beyond last label
try:
_, fullname = targets[i + distance]
except IndexError:
return None
return self.get_symbol(fullname)
def get_unused_symbols(self):
"""return all symbol names that have not been used"""
unused_symbols = {} # filename x symbols
for symbol, (_, unused) in self.symbols.items():
if not unused or symbol[:2] == '_%':
continue # skip used symbols and internal names
try:
lino, filename = self.symbol_def_location[symbol]
name = f'{symbol}:{lino}'
except (TypeError, KeyError):
filename = None
name = symbol
unused_symbols.setdefault(filename, []).append(name)
return unused_symbols
def is_symbol(self, name):
return name in self.symbols or name in self.definitions
def list(self, equ=False):
"""generate symbols"""
symlist = []
for symbol in sorted(self.symbols):
if symbol[0] == '$' or symbol[0] == '_':
continue # skip local and internal symbols
value, _ = self.symbols[symbol]
symlist.append((symbol, Address.val(value)))
fmt = '{}:\n EQU >{:04X}' if equ else ' {:.<20} >{:04X}'
return '\n'.join(fmt.format(*symbol) for symbol in symlist)
def clone(self):
"""internal method"""
return {val: sym for val, (sym, _) in self.symbols.items()}
def diff(self, syms1, syms2):
"""internal method"""
print('*** ' + str(self.pass_no))
for sym in syms1:
val1 = Address.val(syms1[sym])
val2 = Address.val(syms2[sym])
if val1 != val2:
print(f'{sym}: >{val1:X} -> >{val2:X}')
# Parser and Preprocessor
class SyntaxVariant:
def __init__(self, **entries):
self.__dict__.update(entries)
class Syntax:
"""various syntax conventions"""
@staticmethod
def get(style):
try:
return getattr(Syntax, style)
except AttributeError:
raise AsmError('Unknown syntax style ' + style)
xdt99 = SyntaxVariant( # includes RAG and RyteData
ga=r'(?:(@|\*|V@|V\*|G@)|(#|R@))([^(]+)(?:\(@?([^)]+)\))?$',
gprefix='G@',
moveops=r'([^,]+),\s*([^,]+),\s*([^,]+)$',
tdelim="'",
# regex replacements applied to escaped mnemonic and op fields
repls=[
(r'^HMOVE\b', 'HSTR'), # renamed HMOVE -> HSTR
(r'^ORG\b', 'AORG'), # TI
(r'^TITL\b', 'TITLE'), # RYTE DATA
(r'^HTEX\b', 'HTEXT'),
(r'^VTEX\b', 'VTEXT'),
(r'^HCHA\b', 'HCHAR'),
(r'^VCHA\b', 'VCHAR'),
(r'^SCRO\b', 'BIAS'),
(r'^CARR\b', 'CARRY'),
(r'&([01]+)', r':\1'),
(r'^IDT\b', 'TITLE'), # RAG
(r'^IO\b', 'I/O'),
(r'^IROW\b', 'ROW+'),
(r'^ICOL\b', 'COL+')
]
)
mizapf = SyntaxVariant(
ga=r'(?:([@*]|VDP[@*]|GR[OA]M@)|(VREG))([^(]+)(?:\(@?([^)]+)\))?$',
gprefix='GROM@',
moveops=r'(.+)\s+BYTES\s+FROM\s+(.+)\s+TO\s+(.+)$',
tdelim='"',
repls=[
(r'^PRINTH\s+(.+)\sTIMES\s+(.+)\b', r'HCHAR \1,\2'),
(r'^PRINTV\s+(.+)\sTIMES\s+(.+)\b', r'VCHAR \1,\2'),
(r'^FOR\s+(.+)\sTIMES\s+DO\b', r'FOR \1'),
(r'^PRINTH\b', r'HTEXT'),
(r'^PRINTV\b', r'VTEXT'),
(r'^DOWN\b', 'ROW+'),
(r'^RIGHT\b', 'COL+'),
(r'^END\b', 'FEND'),
(r'^HMOVE\b', 'HSTR'),
(r'^XGPL\b', 'BYTE')
]
)
class Preprocessor:
"""xdt99-specific preprocessor extensions"""
def __init__(self, parser):
self.parser = parser
self.parse = True
self.parse_branches = []
self.parse_else = False
self.parse_macro = None
self.parse_repeat = False # parsing repeat section?
self.repeat_count = 0 # number of repetitions
self.macros = {'VERS': [f" text '{VERSION}'"]} # macros defined (with predefined macros)
def args(self, ops):
lhs = self.parser.expression(ops[0], for_pass_0=True)
rhs = self.parser.expression(ops[1], for_pass_0=True) if len(ops) > 1 else 0
return lhs, rhs
def DEFM(self, code, ops):
"""define macro"""
if len(ops) != 1:
raise AsmError('Invalid syntax')
self.parse_macro = ops[0]
if self.parse_macro in ('DEFM', 'ENDM', 'IFDEF', 'IFNDEF', 'IFEQ', 'IFNE', 'IFGE', 'IFGT', 'IFLE', 'IFLT',
'ELSE', 'ENDIF', 'REPT', 'ENDR', 'PRINT', 'ERROR'):
raise AsmError('Invalid macro name')
if self.parse_macro in self.macros:
raise AsmError('Duplicate macro name')
self.macros[self.parse_macro] = []
def ENDM(self, code, ops):
raise AsmError('Found .ENDM without .DEFM')
def REPT(self, asm, ops):
"""repeat section n times"""
self.repeat_count = self.parser.expression(ops[0], for_pass_0=True)
self.parse_repeat = True
self.parse_macro = '.rept' # use lower case name as impossible macro name
self.macros['.rept'] = [] # collect repeated section as '.rept' macro
def ENDR(self, asm, ops):
raise AsmError('Found .ENDR without .REPT')
def IFDEF(self, code, ops):
self.parse_branches.append((self.parse, self.parse_else))
self.parse = code.symbols.is_symbol(ops[0]) if self.parse else None
self.parse_else = False
def IFNDEF(self, code, ops):
self.parse_branches.append((self.parse, self.parse_else))
self.parse = not code.symbols.is_symbol(ops[0]) if self.parse else None
self.parse_else = False
def IFEQ(self, code, ops):
self.parse_branches.append((self.parse, self.parse_else))
self.parse = self.cmp(*self.args(ops)) == 0 if self.parse else None
self.parse_else = False
def IFNE(self, code, ops):
self.parse_branches.append((self.parse, self.parse_else))
self.parse = self.cmp(*self.args(ops)) != 0 if self.parse else None
self.parse_else = False
def IFGT(self, code, ops):
self.parse_branches.append((self.parse, self.parse_else))
self.parse = self.cmp(*self.args(ops)) > 0 if self.parse else None
self.parse_else = False
def IFGE(self, code, ops):
self.parse_branches.append((self.parse, self.parse_else))
self.parse = self.cmp(*self.args(ops)) >= 0 if self.parse else None
self.parse_else = False
def ELSE(self, code, ops):
if not self.parse_branches or self.parse_else:
raise AsmError("Misplaced .else")
self.parse = not self.parse if self.parse is not None else None
self.parse_else = True
def ENDIF(self, code, ops):
try:
self.parse, self.parse_else = self.parse_branches.pop()
except IndexError:
raise AsmError('Misplaced .endif')
def ERROR(self, code, ops):
if self.parse:
raise AsmError('Error state')
@staticmethod
def cmp(x, y):
return (Address.val(x) > Address.val(y)) - (Address.val(x) < Address.val(y))
def instantiate_macro_args(self, text, restore_lits=False):
"""replace macro parameters by macro arguments"""
def get_macro_text(match):
try:
inst_text = self.parser.macro_args[int(match.group(1)) - 1]
return self.parser.restore(inst_text) if restore_lits else inst_text
except IndexError:
return match.group()
try:
return re.sub(r'\$(\d+)', get_macro_text, text)
except ValueError:
return text
def instantiate_line(self, line):
# temporary kludge, breaks comments
parts = re.split(r"('(?:[^']|'')*'|\'[^\']*\')", line)
parts[::2] = [self.instantiate_macro_args(p, restore_lits=True) for p in parts[::2]]
return ''.join(parts)
def process_repeat(self, mnemonic, line):
if mnemonic == '.ENDR':
self.parse_repeat = False
self.parse_macro = None
self.macros['.rept'] *= self.repeat_count # repeat section
self.parser.open(macro='.rept', macro_args=()) # open '.rept' macro
elif mnemonic == '.REPT':
raise AsmError('Cannot repeat within repeat section')
elif mnemonic == '.DEFM':
raise AsmError('Cannot define macro within repeat section')
elif mnemonic == '.ENDM':
raise AsmError('Found .ENDM without .DEFM')
else:
self.macros[self.parse_macro].append(line)
return False, None, None
def process_macro(self, mnemonic, line):
if mnemonic == '.ENDM':
self.parse_macro = None
elif mnemonic == '.DEFM':
raise AsmError('Cannot define macro within macro')
elif mnemonic == '.REPT':
raise AsmError('Cannot repeat section within macro')
elif mnemonic == '.ENDR':
raise AsmError('Found .ENDR without .REPT')
else:
self.macros[self.parse_macro].append(line)
return False, None, None
def process(self, asm, label, mnemonic, operands, line):
"""process preprocessor directive"""
if self.parse_repeat:
return self.process_repeat(mnemonic, line)
if self.parse_macro:
return self.process_macro(mnemonic, line)
if self.parse and asm.parser.in_macro_instantiation and operands:
operands = [self.instantiate_macro_args(op) for op in operands]
line = self.instantiate_line(line) # only for display
if mnemonic and mnemonic[0] == '.':
asm.process_label(label)
name = mnemonic[1:]
if name in self.macros:
if self.parse:
self.parser.open(macro=name, macro_args=operands, label=label, line=line)
else:
try:
fn = getattr(Preprocessor, name)
except AttributeError:
raise AsmError('Invalid preprocessor directive')
try:
fn(self, asm, operands)
except (IndexError, ValueError):
raise AsmError('Syntax error')
return False, None, None
else:
return self.parse, operands, line
class IntmLine:
"""intermediate source line"""
OPEN = '$OPEN$' # constants inserted into source to denote new or resumes source units
RESUME = '$RESM$'
def __init__(self, mnemonic, lino=0, lidx=0, label=None, operands=(), line=None, filename=None, path=None,
is_statement=False):
self.label = label
self.mnemonic = mnemonic
self.operands = operands
self.lino = lino
self.lidx = lidx
self.line = line
self.filename = filename
self.path = path
self.is_statement = is_statement
class Parser:
"""scanner and parser class"""
def __init__(self, symbols, console, syntax, path, includes=None, strict=False, relaxed=False):
self.symbols = symbols
self.console = console
self.syntax = Syntax.get(syntax)
self.path = self.initial_path = path # current file path, used for includes
self.includes = includes or [] # do not include '.'
self.strict = strict
self.relaxed = relaxed
self.prep = Preprocessor(self)
self.text_literals = []
self.filename = None # current file name
self.source = None # current source file in pass 0
self.intermediate_source = [] # preprocessed GPL source file
self.macro_args = []
self.in_macro_instantiation = False
self.lino = -1 # current line number
self.srcline = None
self.suspended_files = []
self.fmt_mode = False # parsing in FMT instruction?
self.for_loops = [] # tracks open for loops
def reset(self):
"""reset state for new assembly pass"""
self.fmt_mode = False
self.for_loops = []
self.path = self.initial_path
def open(self, filename=None, macro=None, macro_args=None, label=None, line=None):
"""open new source file or macro buffer"""
if len(self.suspended_files) > 100:
raise AsmError('Too many nested files or macros')
if filename:
newfile = '-' if filename == '-' else self.find(self.fix_path_separator(filename))
# CAUTION: don't suspend source if file does not exist!
else:
newfile = None
if self.source is not None:
self.suspended_files.append((self.filename, self.path, self.source,
self.in_macro_instantiation, self.macro_args, self.lino))
if filename:
self.path, self.filename = os.path.split(newfile)
self.source = Util.readlines(newfile)
self.in_macro_instantiation = False
else:
self.source = self.prep.macros[macro]
self.macro_args = macro_args or []
self.in_macro_instantiation = True
if label or line:
self.intermediate_source.append(IntmLine('.', lino=self.lino, label=label, line=line))
self.filename = filename or macro
self.lino = 0
self.intermediate_source.append(IntmLine(IntmLine.OPEN, filename=self.filename))
def fix_path_separator(self, path):
"""replaces foreign file separators with system one"""
if os.path.sep not in path:
# foreign path
foreign_sep = '\\' if os.path.sep == '/' else '/'
return path.replace(foreign_sep, os.path.sep)
else:
# system path (does not recognize foreign path with \-escaped chars on Linux or regular / chars on Windows)
return path
def resume(self):
"""close current source file and resume previous one"""
try:
(self.filename, self.path, self.source,
self.in_macro_instantiation, self.macro_args, self.lino) = self.suspended_files.pop()
self.intermediate_source.append(IntmLine(IntmLine.RESUME, filename=self.filename))
return True
except IndexError:
self.source = None # indicates end-of-source to pass; keep self.path!
return False
def stop(self):
"""stop reading source"""
while self.resume():
pass
def find(self, filename):
"""locate file that matches native filename or TI filename"""
include_path = self.includes + ([self.path] if self.path else []) # self.path changes during assembly
ti_name = re.match(r'(?:DSK\d|DSK\.[^.]+)\.(.*)', filename)
if ti_name:
native_name = ti_name.group(1)
extensions = ['', '.g99', '.G99', '.gpl', '.GPL', '.g', '.G']
else:
native_name = filename
extensions = ['']
for i in include_path:
for e in extensions:
include_file = os.path.join(i, native_name + e)
if os.path.isfile(include_file):
return include_file
include_file = os.path.join(i, native_name.lower() + e)
if os.path.isfile(include_file):
return include_file
raise AsmError(f'File not found: {filename}')
def lines(self):
"""get next logical line from source files"""
self.symbols.lidx = 0
while self.source is not None:
try:
line = self.source[self.lino]
self.srcline = line.rstrip()
self.lino += 1
self.symbols.lidx += 1
yield self.lino, self.srcline, self.filename
except IndexError:
self.resume()
def intermediate_lines(self):
"""return preprocessed source code"""
for imline in self.intermediate_source:
self.lino = imline.lino
self.srcline = imline.line
self.filename = imline.filename
self.path = imline.path
self.symbols.lidx = imline.lidx
yield imline
def line(self, line):
"""parse single source line"""
if not line or line[0] == '*':
return None, None, None, None, False