-
Notifications
You must be signed in to change notification settings - Fork 8
/
pyz80.py
executable file
·2011 lines (1668 loc) · 61.9 KB
/
pyz80.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
from __future__ import print_function
from __future__ import division
import math
# TODO: define and assemble macro blocks
# added FILESIZE("filename")
# defs doesn't cause bytes to be written to output unless real data follows
def printusage():
print("pyz80 by Andrew Collier, modified by Simon Owen")
print(" https://github.com/simonowen/pyz80/")
print("Usage:")
print(" pyz80 (options) inputfile(s)")
print("Options:")
print("-o outputfile")
print(" save the resulting disk image at the given path")
print("--nozip")
print(" do not compress the resulting disk image")
print("-I filepath")
print(" Add this file to the disk image before assembling")
print(" May be used multiple times to add multiple files")
print("--obj=outputfile")
print(" save the output code as a raw binary file at the given path")
print("-D symbol")
print("-D symbol=value")
print(" Define a symbol before parsing the source")
print(" (value is integer; if omitted, assume 1)")
print("--exportfile=filename")
print(" Save all symbol information into the given file")
print("--importfile=filename")
print(" Define symbols before assembly, from a file previously exported")
print("--mapfile=filename")
print(" Save address-to-symbol map into the given file")
print("--lstfile=filename")
print(" Produce assembly listing into given file")
print("--case")
print(" treat source labels as case sensitive (as COMET itself did)")
print("--nobodmas")
print(" treat arithmetic operators without precedence (as COMET itself did)")
print("--intdiv")
print(" force all division to give an integer result (as COMET itself did)")
print("-s regexp")
print(" print the value of any symbols matching the given regular expression")
print(" This may be used multiple times to output more than one subset")
print("-e")
print(" use python's own error handling instead of trying to catch parse errors")
def printlicense():
print("This program is free software; you can redistribute it and/or modify")
print("it under the terms of the GNU General Public License as published by")
print("the Free Software Foundation; either version 2 of the License, or")
print("(at your option) any later version.")
print(" ")
print("This program is distributed in the hope that it will be useful,")
print("but WITHOUT ANY WARRANTY; without even the implied warranty of")
print("MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the")
print("GNU General Public License for more details.")
print(" ")
print("You should have received a copy of the GNU General Public License")
print("along with this program; if not, write to the Free Software")
print("Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA")
import getopt
import sys, os, datetime
import array
import fileinput
import re
import gzip
import math # for use by expressions in source files
import random
# Try for native pickle (2.x), fall back on Python version (3.x)
try:
import cPickle as pickle
except ImportError:
import pickle
def new_disk_image():
image = array.array('B')
image.append(0)
targetsize = 80*SPT*2*512
# disk image is arranged as: tr 0 s 1-10, tr 128 s 1-10, tr 1 s 1-10, tr 129 s 1-10 etc
while len(image) < targetsize:
image.extend(image)
while len(image) > targetsize:
image.pop()
return image
def dsk_at(track,side,sector):
return (track*SPT*2+side*SPT+(sector-1))*512
# uses numbering 1-10 for sectors, because SAMDOS internal format also does
def add_file_to_disk_image(image, filename, codestartpage, codestartoffset, execpage=0, execoffset=0, filelength=None, fromfile=None ):
global firstpageoffset, global_currentfile, global_currentline
global_currentfile = 'add file'
global_currentline = ''
if fromfile != None:
modified = datetime.datetime.fromtimestamp(os.path.getmtime(fromfile))
fromfilefile = open(fromfile,'rb')
fromfilefile.seek(0,2)
filelength = fromfilefile.tell()
fromfilefile.seek(0)
fromfile = array.array('B')
fromfile.fromfile(fromfilefile, filelength)
else:
modified = datetime.datetime.now()
sectors_already_used = 0
# we're writing the whole image, so we can take a bit of a shortcut
# instead of reading the entire sector map to find unused space, we can assume all files are contiguous
# and place new files just at the end of the used space
#find an unused directory entry
for direntry in range(4*SPT*2):
dirpos = dsk_at(direntry//(SPT*2),0,1+(direntry%(SPT*2))//2) + 256*(direntry%2)
if image[dirpos] == 0:
break
else:
sectors_already_used += image[dirpos+11]*256 +image[dirpos+12]
else:
fatal ("Too many files for dsk format")
image[dirpos] = 19 # code file
for i in range(10):
image[dirpos+1+i] = ord((filename+" ")[i])
nsectors = math.ceil(( filelength + 9 ) / 510)
image[dirpos+11] = nsectors // 256 # MSB number of sectors used
image[dirpos+12] = nsectors % 256 # LSB number of sectors used
starting_side = (4 + sectors_already_used//SPT)//80
starting_track = (4 + sectors_already_used//SPT)%80
starting_sector = sectors_already_used%SPT + 1
image[dirpos+13] = starting_track + 128*starting_side # starting track
image[dirpos+14] = starting_sector # starting sector
# 15 - 209 sector address map
# write table of used sectors (can precalculate from number of used bits)
while nsectors > 0:
image[dirpos+15 + sectors_already_used//8] |= (1 << (sectors_already_used & 7))
sectors_already_used += 1
nsectors -= 1
# 210-219 MGT future and past (reserved)
image[dirpos+220] = 0 # flags (reserved)
# 221-231 File type information (n/a for code files)
# 232-235 reserved
image[dirpos+236] = codestartpage # start page number
image[dirpos+237] = (codestartoffset%256) # page offset (in section C, 0x8000 - 0xbfff)
image[dirpos+238] = 128 + (codestartoffset // 256)
image[dirpos+239] = filelength//16384 # pages in length
image[dirpos+240] = filelength%256 # file length % 16384
image[dirpos+241] = (filelength%16384)//256
if (execpage>0) :
image[dirpos+242] = execpage # execution address or 255 255 255 (basicpage, L, H - offset in page C)
image[dirpos+243] = execoffset % 256
image[dirpos+244] = (execoffset%16384)//256 + 128
else:
image[dirpos+242] = 255 # execution address or 255 255 255 (basicpage, L, H - offset in page C)
image[dirpos+243] = 255
image[dirpos+244] = 255
image[dirpos+245] = modified.day
image[dirpos+246] = modified.month
image[dirpos+247] = modified.year % 100 + 100
image[dirpos+248] = modified.hour
image[dirpos+249] = modified.minute
side = starting_side
track = starting_track
sector = starting_sector
fpos = 0
# write file's 9 byte header and file
imagepos = dsk_at(track,side,sector)
# 0 File type 19 for a code file
image[imagepos + 0] = 19
# 1-2 Modulo length Length of file % 16384
image[imagepos + 1] = filelength%256
image[imagepos + 2] = (filelength%16384)//256
# 3-4 Offset start Start address
image[imagepos + 3] = (codestartoffset%256)
image[imagepos + 4] = 128 + (codestartoffset // 256)
# 5-6 Unused
# 7 Number of pages
image[imagepos + 7] = filelength//16384
# 8 Starting page number
image[imagepos + 8] = codestartpage
start_of_file = True
while fpos < filelength:
imagepos = dsk_at(track,side,sector)
unadjustedimagepos = imagepos
if start_of_file:
if filelength > 500:
copylen = 501
else:
copylen = filelength
imagepos += 9
start_of_file = False
else:
if (filelength-fpos) > 509:
copylen = 510
else:
copylen = (filelength-fpos)
if fromfile != None:
image[imagepos:imagepos+copylen] = fromfile[fpos:fpos+copylen]
else:
if ((fpos+firstpageoffset)//16384) == (((fpos+codestartoffset)+copylen-1)//16384):
if memory[codestartpage+(fpos+codestartoffset)//16384] != '':
image[imagepos:imagepos+copylen] = memory[codestartpage+(fpos+firstpageoffset)//16384][(fpos+codestartoffset)%16384 : (fpos+codestartoffset)%16384+copylen]
else:
copylen1 = 16384 - ((fpos+codestartoffset)%16384)
page1 = (codestartpage+(fpos+codestartoffset)//16384)
if memory[page1] != '':
image[imagepos:imagepos+copylen1] = memory[page1][(fpos+codestartoffset)%16384 : ((fpos+codestartoffset)%16384)+copylen1]
if (page1 < 31) and memory[page1+1] != '':
image[imagepos+copylen1:imagepos+copylen] = memory[page1+1][0 : ((fpos+codestartoffset)+copylen)%16384]
fpos += copylen
sector += 1
if sector == (SPT+1):
sector = 1
track += 1
if track == 80:
track = 0
side += 1
if side==2:
fatal("Disk full writing "+filename)
# pointers to next sector and track
if (fpos < filelength):
image[unadjustedimagepos+510] = track + 128*side
image[unadjustedimagepos+511] = sector
def array_bytes(arr):
return arr.tobytes() if hasattr(arr, "tobytes") else arr.tostring()
def save_disk_image(image, pathname):
imagestr = array_bytes(image)
if ZIP:
dskfile = gzip.open(pathname, 'wb')
else:
dskfile = open(pathname, 'wb')
dskfile.write(imagestr)
dskfile.close()
def save_memory(memory, image=None, filename=None):
global firstpage,firstpageoffset
if firstpage==32:
# code was assembled without using a DUMP directive
firstpage = 1
firstpageoffset = 0
if memory[firstpage] != '':
# check that something has been assembled at all
filelength = (lastpage - firstpage + 1) * 16384
filelength -= firstpageoffset
filelength -= 16384-lastpageoffset
if (autoexecpage>0) :
savefilename = ("AUTO" + filename + " ")[:8]+".O"
else:
savefilename = (filename + " ")[:8]+".O"
if image:
add_file_to_disk_image(image,savefilename,firstpage, firstpageoffset, autoexecpage, autoexecorigin, filelength)
else:
save_memory_to_file(filename, firstpage, firstpageoffset, filelength)
def save_file_to_image(image, pathname):
sam_filename = os.path.basename(pathname)
if len(sam_filename)>10:
if sam_filename.count("."):
extpos = sam_filename.rindex(".")
extlen = len(sam_filename)-extpos
sam_filename = sam_filename[:10-extlen] + sam_filename[extpos:]
else:
sam_filename = sam_filename[:10]
add_file_to_disk_image(image,sam_filename, 1, 0, fromfile=pathname)
def save_memory_to_file(filename, firstusedpage, firstpageoffset, filelength):
objfile = open(filename, 'wb')
flen = filelength
page = firstusedpage
offset = firstpageoffset
while flen:
wlen = min(16384-offset, flen)
if memory[page] != "":
pagestr = array_bytes(memory[page])
objfile.write(pagestr[offset:offset+wlen])
else:
# write wlen nothings into the file
objfile.seek(wlen,1)
flen -= wlen
page += 1
offset=0
objfile.close()
def warning(message):
print(global_currentfile, 'warning:', message)
print('\t', global_currentline.strip())
def fatal(message):
print(global_currentfile, 'error:', message)
print ('\t', global_currentline.strip())
sys.exit(1)
def expand_symbol(sym):
while 1:
match = re.search(r'\{([^\{\}]*)\}', sym)
if match:
value = parse_expression(match.group(1))
sym = sym.replace(match.group(0),str(value))
else:
break
return sym
def file_and_stack(explicit_currentfile=None):
if explicit_currentfile==None:
explicit_currentfile = global_currentfile
f,l = explicit_currentfile.rsplit(':', 1)
s=''
for i in forstack:
s=s+"^"+str(i[2])
return f+s+':'+l
def set_symbol(sym, value, explicit_currentfile=None, is_label=False):
symorig = expand_symbol(sym)
sym = symorig if CASE else symorig.upper()
if sym[0]=='@':
sym = sym + '@' + file_and_stack(explicit_currentfile=explicit_currentfile)
symboltable[sym] = value
if sym != symorig:
symbolcase[sym] = symorig
if is_label:
labeltable[sym] = value
def get_symbol(sym):
symorig = expand_symbol(sym)
sym = symorig if CASE else symorig.upper()
if sym[0]=='@':
if (sym + '@' + file_and_stack()) in symboltable:
return symboltable[sym + '@' + file_and_stack()]
else:
if len(sym) > 1 and (sym[1]=='-' or sym[1]=='+'):
directive = sym[1]
sym = sym[0]+sym[2:]
else:
directive=''
reqfile,reqline = file_and_stack().rsplit(':', 1)
reqline = int(reqline)
closestKey = None
for key in symboltable:
if (sym+'@'+reqfile+":").startswith(key.rsplit(":",1)[0]+":") or (sym+'@'+reqfile+":").startswith(key.rsplit(":",1)[0]+"^"):
# key is allowed fewer layers of FOR stack, but any layers it has must match
# ensure a whole number (ie 1 doesn't match 11) by forceing a colon or hat
symfile,symline = key.rsplit(':', 1)
symline=int(symline)
difference = reqline - symline
if (difference < 0 or directive != '+') and (difference > 0 or directive != '-') and ((closestKey == None) or (abs(difference) < closest)):
closest = abs(difference)
closestKey = key
if (not closestKey) and (directive == '-'):
global include_stack
use_include_stack = include_stack
use_include_stack.reverse()
# try searching up the include stack
for include_item in use_include_stack:
include_file, include_line = include_item[1].rsplit(":",1)
if not closestKey:
for key in symboltable:
if (sym+'@'+include_file+":").startswith(key.rsplit(":",1)[0]+":") or (sym+'@'+include_file+":").startswith(key.rsplit(":",1)[0]+"^"):
# key is allowed fewer layers of FOR stack, but any layers it has must match
# ensure a whole number (ie 1 doesn't match 11) by forceing a colon or hat
symfile,symline = key.rsplit(':', 1)
symline=int(symline)
difference = int(include_line) - symline
if (difference < 0 or directive != '+') and (difference > 0 or directive != '-') and ((closestKey == None) or (abs(difference) < closest)):
closest = abs(difference)
closestKey = key
if closestKey != None:
sym = closestKey
if sym in symboltable:
symusetable[sym] = symusetable.get(sym,0)+1
return symboltable[sym]
return None
def parse_expression(arg, signed=0, byte=0, word=0, silenterror=0):
if ',' in arg:
if silenterror:
return ''
fatal("Erroneous comma in expression"+arg)
while 1:
match = re.search('"(.)"', arg)
if match:
arg = arg.replace('"'+match.group(1)+'"',str(ord(match.group(1))))
else:
break
while 1:
match = re.search(r'defined\s*\(\s*(.*?)\s*\)', arg, re.IGNORECASE)
if match:
result = (get_symbol(match.group(1)) != None)
arg = arg.replace(match.group(0),str(int(result)))
else:
break
arg = arg.replace('$','('+str(origin)+')')
arg = arg.replace('%','0b') # COMET syntax for binary literals (parsed later, change to save confusion with modulus)
arg = arg.replace('\\','%') # COMET syntax for modulus
arg = re.sub(r'&([0-9a-fA-F]+\b)', r'0x\g<1>', arg) # COMET syntax for hex numbers
if INTDIV:
arg = re.sub(r'(?<!/)/(?!/)', r'//', arg) # COMET integer division
# don't do these except at the start of a token:
arg = re.sub(r'\b0X', '0x', arg) # darnit, this got capitalized
arg = re.sub(r'\b0B', '0b', arg) # darnit, this got capitalized
# if the argument contains letters at this point,
# it's a symbol which needs to be replaced
testsymbol=''
argcopy = ''
incurly = 0
inquotes = False
for c in arg+' ':
if c.isalnum() or c in '"_.@{}' or (c=="+" and testsymbol=='@') or (c=="-" and testsymbol=='@') or incurly or inquotes:
testsymbol += c
if c=='{':
incurly += 1
elif c=='}':
incurly -= 1
elif c=='"':
inquotes = not inquotes
else:
if (testsymbol != ''):
if not testsymbol[0].isdigit():
result = get_symbol(testsymbol)
if (result != None):
testsymbol = str(result)
elif testsymbol[0] == '"' and testsymbol[-1]=='"':
# string literal used in some expressions
pass
else:
understood = 0
# some of python's math expressions should be available to the parser
if not understood and testsymbol.lower() != 'e':
parsestr = 'math.'+testsymbol.lower()
try:
eval(parsestr)
understood = 1
except:
understood = 0
if not understood:
parsestr = 'random.'+testsymbol.lower()
try:
eval(parsestr)
understood = 1
except:
understood = 0
if testsymbol in ["FILESIZE"]:
parsestr = 'os.path.getsize'
understood = 1
if not understood :
if silenterror:
return ''
fatal("Error in expression "+arg+": Undefined symbol "+expand_symbol(testsymbol))
testsymbol = parsestr
elif testsymbol[0]=='0' and len(testsymbol)>2 and testsymbol[1]=='b':
# binary literal
literal = 0
for digit in testsymbol[2:]:
literal *= 2
if digit == '1':
literal += 1
elif digit != '0':
fatal("Invalid binary digit '"+digit+"'")
testsymbol = str(literal)
elif testsymbol[0]=='0' and len(testsymbol)>1 and testsymbol[1]!='x':
# literals with leading zero would be treated as octal,
# COMET source files do not expect this
decimal = testsymbol
while decimal[0] == '0' and len(decimal)>1:
decimal = decimal[1:]
testsymbol = decimal
argcopy += testsymbol
testsymbol = ''
argcopy += c
if NOBODMAS:
# add bracket pairs at interesting locations to simulate left-to-right evaluation
aslist = list(argcopy) # turn it into a list so that we can add characters without affecting indexes
bracketstack=[0]
symvalid = False
for c in range (len(aslist)):
if aslist[c] == "(":
bracketstack = [c]+bracketstack
elif aslist[c] == ")":
bracketstack = bracketstack[1:]
elif (not aslist[c].isalnum()) and (not aslist[c]=='.') and (not aslist[c].isspace()) and symvalid:
aslist[c] = ")"+aslist[c]
aslist[bracketstack[0]] = '('+aslist[bracketstack[0]]
symvalid = False
elif aslist[c].isalnum():
symvalid = True
argcopy2=""
for entry in aslist:
argcopy2 += entry
# print(argcopy,"->",argcopy2)
argcopy = argcopy2
narg = int(eval(argcopy))
# print(arg, " -> ",argcopy," == ",narg)
if not signed:
if byte:
if narg < -128 or narg > 255:
warning ("Unsigned byte value truncated from "+str(narg))
narg %= 256
elif word:
if narg < -32768 or narg > 65535:
warning ("Unsigned word value truncated from "+str(narg))
narg %= 65536
return narg
def double(arg, allow_af_instead_of_sp=0, allow_af_alt=0, allow_index=1):
# decode double register [bc, de, hl, sp][ix,iy] --special: af af'
double_mapping = {'BC':([],0), 'DE':([],1), 'HL':([],2), 'SP':([],3), 'IX':([0xdd],2), 'IY':([0xfd],2), 'AF':([],5), "AF'":([],4) }
rr = double_mapping.get(arg.strip().upper(),([],-1))
if (rr[1]==3) and allow_af_instead_of_sp:
rr = ([],-1)
if rr[1]==5:
if allow_af_instead_of_sp:
rr = ([],3)
else:
rr = ([],-1)
if (rr[1]==4) and not allow_af_alt:
rr = ([],-1)
if (rr[0] != []) and not allow_index:
rr = ([],-1)
return rr
def single(arg, allow_i=0, allow_r=0, allow_index=1, allow_offset=1, allow_half=1):
#decode single register [b,c,d,e,h,l,(hl),a][(ix {+c}),(iy {+c})]
single_mapping = {'B':0, 'C':1, 'D':2, 'E':3, 'H':4, 'L':5, 'A':7, 'I':8, 'R':9, 'IXH':10, 'IXL':11, 'IYH':12, 'IYL':13 }
m = single_mapping.get(arg.strip().upper(),-1)
prefix=[]
postfix=[]
if m==8 and not allow_i:
m = -1
if m==9 and not allow_r:
m = -1
if allow_half:
if m==10:
prefix = [0xdd]
m = 4
if m==11:
prefix = [0xdd]
m = 5
if m==12:
prefix = [0xfd]
m = 4
if m==13:
prefix = [0xfd]
m = 5
else:
if m >= 10 and m <= 13:
m = -1
if m==-1 and re.search(r"\A\s*\(\s*HL\s*\)\s*\Z", arg, re.IGNORECASE):
m = 6
if m==-1 and allow_index:
match = re.search(r"\A\s*\(\s*(I[XY])\s*\)\s*\Z", arg, re.IGNORECASE)
if match:
m = 6
prefix = [0xdd] if match.group(1).lower() == 'ix' else [0xfd]
postfix = [0]
elif allow_offset:
match = re.search(r"\A\s*\(\s*(I[XY])\s*([+-].*)\s*\)\s*\Z", arg, re.IGNORECASE)
if match:
m = 6
prefix = [0xdd] if match.group(1).lower() == 'ix' else [0xfd]
if p==2:
offset = parse_expression(match.group(2), byte=1, signed=1)
if offset < -128 or offset > 127:
fatal ("invalid index offset: "+str(offset))
postfix = [(offset + 256) % 256]
else:
postfix = [0]
return prefix,m,postfix
def condition(arg):
# decode condition [nz, z, nc, c, po, pe, p, m]
condition_mapping = {'NZ':0, 'Z':1, 'NC':2, 'C':3, 'PO':4, 'PE':5, 'P':6, 'M':7 }
return condition_mapping.get(arg.upper(),-1)
def dump(bytes):
def initpage(page):
memory[page] = array.array('B')
memory[page].append(0)
while len(memory[page]) < 16384:
memory[page].extend(memory[page])
global dumppage, dumporigin, dumpspace_pending, lstcode, listingfile
if (p==2):
if dumpspace_pending > 0:
if memory[dumppage]=='':
initpage(dumppage)
dumporigin += dumpspace_pending
dumppage += dumporigin // 16384
dumporigin %= 16384
dumpspace_pending = 0
if memory[dumppage]=='':
initpage(dumppage)
lstcode = ""
for b in bytes:
# if b<0 or b>255:
# warning("Dump byte out of range")
memory[dumppage][dumporigin] = b
if listingfile != None:
lstcode=lstcode+"%02X "%(b)
dumporigin += 1
if dumporigin == 16384:
dumporigin = 0
dumppage += 1
if memory[dumppage]=='':
initpage(dumppage)
def check_args(args,expected):
if args=='':
received = 0
else:
received = len(args.split(','))
if expected!=received:
fatal("Opcode wrong number of arguments, expected "+str(expected)+" received "+str(args))
def op_ORG(p,opargs):
global origin
check_args(opargs,1)
origin = parse_expression(opargs, word=1)
return 0
def op_DUMP(p,opargs):
global dumppage, dumporigin, dumpused, firstpage, firstpageoffset, dumpspace_pending
if dumpused:
check_lastpage()
dumpused = True
dumpspace_pending = 0
if ',' in opargs:
page,offset = opargs.split(',',1)
offset = parse_expression(offset, word=1)
dumppage = parse_expression(page) + (offset//16384)
dumporigin = offset % 16384
else:
offset = parse_expression(opargs)
if (offset<16384):
fatal("DUMP value out of range")
dumppage = (offset//16384) - 1
dumporigin = offset % 16384
if ((dumppage*16384 + dumporigin) < (firstpage*16384 + firstpageoffset)):
firstpage = dumppage
firstpageoffset = dumporigin
return 0
def op_PRINT(p, opargs):
text = []
for expr in opargs.split(","):
if expr.strip().startswith('"'):
text.append(expr.strip().rstrip()[1:-1])
else:
a = parse_expression(expr, silenterror=True)
if a:
text.append(str(a))
else:
text.append("?")
print(global_currentfile, "PRINT: ", ",".join(text))
return 0
def check_lastpage():
global lastpage, lastpageoffset
if dumppage > lastpage:
lastpage = dumppage
lastpageoffset = dumporigin
elif (dumppage == lastpage) and (dumporigin > lastpageoffset):
lastpageoffset = dumporigin
def op_AUTOEXEC(p,opargs):
global autoexecpage, autoexecorigin
check_args(opargs,0)
if (p==2):
if (autoexecpage>0 or autoexecorigin>0):
fatal("AUTOEXEC may only be used once.")
autoexecpage = dumppage + 1 # basic type page numbering
autoexecorigin = dumporigin
return 0
def op_EQU(p,opargs):
global symboltable
check_args(opargs,1)
if (symbol):
if opargs.upper().startswith("FOR") and (opargs[3].isspace() or opargs[3]=='('):
set_symbol(symbol, 0)
limit = parse_expression(opargs[4:].strip())
if limit < 1:
fatal("FOR range < 1 not allowed")
forstack.append( [symbol,global_currentfile,0,limit] )
else:
if p==1:
set_symbol(symbol, parse_expression(opargs, signed=1, silenterror=1))
else:
expr_result = parse_expression(opargs, signed=1)
existing = get_symbol(symbol)
if existing == '':
set_symbol(symbol, expr_result)
elif existing != expr_result:
fatal("Symbol "+expand_symbol(symbol)+": expected "+str(existing)+" but calculated "+str(expr_result)+", has this symbol been used twice?")
else:
warning("EQU without symbol name")
return 0
def op_NEXT(p,opargs):
global global_currentfile
check_args(opargs,1)
foritem = forstack.pop()
if opargs != foritem[0]:
fatal("NEXT symbol "+opargs+" doesn't match FOR: expected "+foritem[0])
foritem[2] += 1
set_symbol(foritem[0], foritem[2], explicit_currentfile=foritem[1])
if foritem[2] < foritem[3]:
global_currentfile = foritem[1]
forstack.append(foritem)
return 0
def op_ALIGN(p,opargs):
global dumpspace_pending
check_args(opargs,1)
align = parse_expression(opargs)
if align<1:
fatal("Invalid alignment")
elif (align & (-align)) != align:
fatal("Alignment is not a power of 2")
s = (align - origin%align)%align
dumpspace_pending += s
return s
def op_DS(p,opargs):
return op_DEFS(p,opargs)
def op_DEFS(p,opargs):
global dumppage, dumporigin, dumpspace_pending
check_args(opargs,1)
if opargs.upper().startswith("ALIGN") and (opargs[5].isspace() or opargs[5]=='('):
return op_ALIGN(p,opargs[5:].strip())
s = parse_expression(opargs)
if s<0:
fatal("Allocated invalid space < 0 bytes ("+str(s)+")")
dumpspace_pending += s
return s
def op_DB(p,opargs):
return op_DEFB(p,opargs)
def op_DEFB(p,opargs):
s = opargs.split(',')
if (p==2):
for b in s:
byte=(parse_expression(b, byte=1, silenterror=1))
if byte=='':
fatal("Didn't understand DB or character constant "+b)
else:
dump([byte])
return len(s)
def op_DW(p,opargs):
return op_DEFW(p,opargs)
def op_DEFW(p,opargs):
s = opargs.split(',')
if (p==2):
for b in s:
b=(parse_expression(b, word=1))
dump([b%256, b//256])
return 2*len(s)
def op_DM(p,opargs):
return op_DEFM(p,opargs)
def op_DEFM(p,opargs):
messagelen = 0
if opargs.strip()=="44" or opargs=="(44)":
dump ([44])
messagelen = 1
else:
matchstr = opargs
while matchstr.strip():
match = re.match(r'\s*\"(.*)\"(\s*,)?(.*)', matchstr)
if not match:
match = re.match(r'\s*([^,]*)(\s*,)?(.*)', matchstr)
byte=(parse_expression(match.group(1), byte=1, silenterror=1))
if byte=='':
fatal("Didn't understand DM character constant "+match.group(1))
elif p==2:
dump([byte])
messagelen += 1
else:
message = list(match.group(1))
if p==2:
for i in message:
dump ([ord(i)])
messagelen += len(message)
matchstr = match.group(3)
if match.group(3) and not match.group(2):
matchstr = '""' + matchstr
# For cases such as DEFM "message with a "" in it"
# I can only apologise for this, this is an artefact of my parsing quotes
# badly at the top level but it's too much for me to go back and refactor it all.
# Of course, it would have helped if Comet had had sane quoting rules in the first place.
return messagelen
def op_MDAT(p,opargs):
global dumppage, dumporigin
match = re.search(r'\A\s*\"(.*)\"\s*\Z', opargs)
filename = os.path.join(global_path, match.group(1))
try:
mdatfile = open(filename,'rb')
except:
fatal("Unable to open file for reading: "+filename)
mdatfile.seek(0,2)
filelength = mdatfile.tell()
if p==1:
dumporigin += filelength
dumppage += dumporigin // 16384
dumporigin %= 16384
elif p==2:
mdatfile.seek(0)
mdatafilearray = array.array('B')
mdatafilearray.fromfile(mdatfile, filelength)
dump(mdatafilearray)
mdatfile.close()
return filelength
def op_INCLUDE(p,opargs):
global global_path, global_currentfile
global include_stack
match = re.search(r'\A\s*\"(.*)\"\s*\Z', opargs)
filename = match.group(1)
include_stack.append((global_path, global_currentfile))
assembler_pass(p, filename)
global_path, global_currentfile = include_stack.pop()
return 0
# global origin has already been updated
def op_FOR(p,opargs):
args = opargs.split(',',1)
limit = parse_expression(args[0])
bytes = 0
for iterate in range(limit):
symboltable['FOR'] = iterate
if CASE:
symboltable['for'] = iterate
bytes += assemble_instruction(p,args[1].strip())
if limit != 0:
del symboltable['FOR']
if CASE:
del symboltable['for']
return bytes
def op_noargs_type(p,opargs,instr):
check_args(opargs,0)
if (p==2):
dump(instr)
return len(instr)
def op_ASSERT(p,opargs):
check_args(opargs,1)
if (p==2):
value = parse_expression(opargs)
if value == 0:
fatal("Assertion failed ("+opargs+")")
return 0
def op_NOP(p,opargs):