-
Notifications
You must be signed in to change notification settings - Fork 0
/
sdasm.py
3874 lines (3365 loc) · 156 KB
/
sdasm.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
"""
ToDo/Issues:
* changing output on first pass affects second pass
for example, using inesprg
* diff can give wrong addresses depending on bank
* create large test .asm
* text mapping
- named textmaps, alternate formats
* option to automatically localize labels in macros
* namespaces
- namespace directive
- use namespaces when defining/specifying labels or symbols
* segment and related directives
* line numbers in errors
* handle negative numbers differently?
* implement Asar's stddefines.txt
* handle relative unlabeled jumps
ex: bcc $79
* allow some awkward lack of spaces: "bne+"
* DONE *, should add tests
* handle expressions in macro arguments
* make it so insert shows added bytes in list file
* fix issue with using org in chr space as the first thing
"""
from array import array
import math, os, sys
# hacky fix for import getting confused
# with NESBuilder's include module
if 'include' in sys.modules:
sys.path.append('/SpiderDaveAsm')
try:
from . import include
except:
import include
Cfg = include.Cfg
ips = include.ips
GG = include.GG
ld65cfg = include.ld65cfg
import time
from datetime import date, datetime
import re
import pathlib
import operator
from math import sqrt
import random
from textwrap import dedent
from collections import deque
import traceback
try:
from PIL import Image, ImageOps
PIL = True
except Exception as e:
PIL = False
print('***', str(e))
try: import numpy as np
except: np = False
# for detecting pyinstaller
frozen = (getattr(sys, 'frozen', False) and hasattr(sys, '_MEIPASS'))
initialFolder = os.getcwd()
if np:
usenp = True
# need better code for slicing with numpy.
# just disable for now.
usenp = False
version = dict(
stage = 'alpha',
buildDate = date.today().strftime('%Y.%m.%d'),
author = 'SpiderDave',
url = 'https://github.com/SpiderDave/SpiderDaveAsm',
)
version.update(version = 'v{} {}'.format(version.get('buildDate'), version.get('stage')))
defaultPalette = [
[116, 116, 116], [36, 24, 140], [0, 0, 168], [68, 0, 156],[140, 0, 116],
[168, 0, 16],[164, 0, 0],[124, 8, 0],[64, 44, 0],[0, 68, 0],[0, 80, 0],
[0, 60, 20],[24, 60, 92],[0, 0, 0],[0, 0, 0],[0, 0, 0],[188, 188, 188],
[0, 112, 236],[32, 56, 236],[128, 0, 240],[188, 0, 188],[228, 0, 88],
[216, 40, 0],[200, 76, 12],[136, 112, 0],[0, 148, 0],[0, 168, 0],
[0, 144, 56],[0, 128, 136],[0, 0, 0],[0, 0, 0],[0, 0, 0],[252, 252, 252],
[60, 188, 252],[92, 148, 252],[204, 136, 252],[244, 120, 252],
[252, 116, 180],[252, 116, 96],[252, 152, 56],[240, 188, 60],
[128, 208, 16],[76, 220, 72],[88, 248, 152],[0, 232, 216],[120, 120, 120],
[0, 0, 0],[0, 0, 0],[252, 252, 252],[168, 228, 252],[196, 212, 252],
[212, 200, 252],[252, 196, 252],[252, 196, 216],[252, 188, 176],
[252, 216, 168],[252, 228, 160],[224, 252, 160],[168, 240, 188],
[176, 252, 204],[156, 252, 240],[196, 196, 196],[0, 0, 0],[0, 0, 0],
]
def replaceStringByIndex(text,startIndex=0,endIndex=0,replacement=''):
l = list(text)
l[startIndex:endIndex]=replacement
return''.join(l)
def makeSurePathExists(path):
pathlib.Path(path).mkdir(parents=True, exist_ok=True)
def elapsed(start, end=False):
if not end:
end = time.time()
hours, rem = divmod(end-start, 3600)
minutes, seconds = divmod(rem, 60)
return "{:0>2}:{:0>2}:{:05.2f}".format(int(hours),int(minutes),seconds)
def findAll(haystack, needle):
return [i for i in range(0, len(haystack)) if haystack[i:].startswith(needle)]
def getIndent(haystack, start=0):
return start+(len(haystack[start:]) - len(haystack[start:].lstrip()))
def bestColorMatch(rgb, colors):
r, g, b = rgb[:3]
color_diffs = []
for color in colors:
cr, cg, cb = color
color_diff = sqrt(abs(r - cr)**2 + abs(g - cg)**2 + abs(b - cb)**2)
color_diffs.append((color_diff, color))
return colors.index(min(color_diffs)[1])
def imageToCHRData(f, colors=False, xOffset=0,yOffset=0, rows=False, cols=False, nTiles=False, shatter = False):
try:
with Image.open(f) as im:
px = im.convert('RGB').load()
#px = im.load()
except:
print("error loading image")
return
width, height = im.size
if rows!=False:
height = rows*8
if cols!=False:
width = cols*8
w = math.floor(width/8)*8
h = math.floor(height/8)*8
if nTiles==False:
nTiles = int(w/8 * h/8)
if shatter:
altPalettes = dict(
gray = [0x0f, 0x2d, 0x10, 0x30],
steve = [0x0f, 0x0b, 0x2a, 0x37],
steveAlt = [0x0f, 0x0b, [118,192,0], 0x37],
hud = [0x0f, 0x15, 0x26, 0x37],
brown = [0x0f, 0x17, 0x27, 0x37],
yychr = [0x0f, [0x8c, 0x63, 0x21], [0xad, 0xb5, 0x31], [0xc6, 0xe7, 0x9c]],
)
for k, pal in altPalettes.items():
altPalettes.update({k:[assembler.palette[x] if isinstance(x, int) else x for x in pal]})
out = []
for t in range(nTiles):
tile = [[]]*16
for y in range(8):
tile[y] = 0
tile[y+8] = 0
for x in range(8):
try:
c = list(px[xOffset + x, yOffset + y])
except:
c = [0,0,0]
i = False
if shatter:
for k, pal in altPalettes.items():
if c[:3] in pal:
i = pal.index(c[:3])
break
if i == False:
i = bestColorMatch(c, colors)
tile[y] += (2**(7-x)) * (i%2)
tile[y+8] += (2**(7-x)) * (math.floor(i/2))
xOffset += 8
if xOffset >=w:
xOffset = 0
yOffset += 8
for i in range(16):
out.append(tile[i])
ret = out
return ret
def importTilemap(tilemap, filename="import.png", offsetX=0, offsetY=0, fileOffset = 0, fileData = False, palette = 'current'):
maxX, maxY = 0, 0
for tile in tilemap.data:
maxX = max(maxX, offsetX + tile.x * tilemap.gridsize + 8)
maxY = max(maxY, offsetY + tile.y * tilemap.gridsize + 8)
# Load image
try:
with Image.open(filename) as img:
px = img.convert('RGB').load()
except:
print("error loading image")
return
width, height = img.size
for tile in tilemap.data:
colors = [assembler.palette[x] for x in tile.get('palette', assembler.currentPalette)]
tileOut = [[]]*16
for y in range(8):
tileOut[y] = 0
tileOut[y+8] = 0
for x in range(8):
if 'h' in tile.flip:
x1 = offsetX + tile.x * tilemap.gridsize + (7-x)
else:
x1 = offsetX + tile.x * tilemap.gridsize + x
if 'v' in tile.flip:
y1 = offsetY + tile.y * tilemap.gridsize + (7-y)
else:
y1 = offsetY + tile.y * tilemap.gridsize + y
try:
c = list(px[x1, y1])
except:
c = [0,0,0]
i = bestColorMatch(c, colors)
tileOut[y] += (2**(7-x)) * (i%2)
tileOut[y+8] += (2**(7-x)) * (math.floor(i/2))
for i in range(16):
fileData[fileOffset+tile.id*16+i] = tileOut[i]
def exportTilemapToImage(tilemap, filename="export.png", offsetX=0, offsetY=0, fileOffset = 0, fileData = False, palette = 'current'):
maxX, maxY = 0, 0
for tile in tilemap.data:
maxX = max(maxX, offsetX + tile.x * tilemap.gridsize + 8)
maxY = max(maxY, offsetY + tile.y * tilemap.gridsize + 8)
# Load or create image
try:
with Image.open(filename) as img:
img.load()
except:
img=Image.new("RGB", size=(8,8))
if (img.width < maxX) or (img.height < maxY):
imgNew = Image.new("RGB", size=(max(img.width, maxX), max(img.height, maxY)))
imgNew.paste(img)
img = imgNew
img.load()
a = np.asarray(img).copy()
for tile in tilemap.data:
colors = tile.get('palette', assembler.currentPalette)
for y in range(8):
for x in range(8):
c=0
if 'h' in tile.flip:
x1 = offsetX + tile.x * tilemap.gridsize + x
else:
x1 = offsetX + tile.x * tilemap.gridsize + (7-x)
if 'v' in tile.flip:
y1 = offsetY + tile.y * tilemap.gridsize + (7-y)
else:
y1 = offsetY + tile.y * tilemap.gridsize + y
if (fileData[fileOffset+tile.id*16+y] & (1<<x)):
c=c+1
if (fileData[fileOffset+tile.id*16+y+8] & (1<<x)):
c=c+2
a[y1][x1] = assembler.palette[colors[c]]
img = Image.fromarray(a)
img.save(filename)
def exportCHRDataToImage(filename="export.png", fileData=False, colors=(0x0f,0x21,0x11,0x01)):
colors=assembler.currentPalette
if not fileData:
print('no filedata')
fileData = "\x00" * 0x1000
if type(fileData) is str:
fileData = [ord(x) for x in fileData]
nTiles = int(len(fileData) / 16)
# Load or create image
try:
with Image.open(filename) as img:
img.load()
except:
img=Image.new("RGB", size=(128,128))
img.load()
a = np.asarray(img).copy()
for tile in range(nTiles):
for y in range(8):
for x in range(8):
c=0
x1=tile%16*8+(7-x)
y1=math.floor(tile/16)*8+y
if (fileData[tile*16+y] & (1<<x)):
c=c+1
if (fileData[tile*16+y+8] & (1<<x)):
c=c+2
a[y1][x1] = assembler.palette[colors[c]]
img = Image.fromarray(a)
img.save(filename)
def makeList(item):
if type(item)!=list:
return flattenList([item])
else:
return flattenList(item)
def flattenList(k):
result = list()
for i in k:
#if '__iter__' in dir(i): # Should be better, but want to test
if isinstance(i,list):
result.extend(flattenList(i))
else:
result.append(i)
return result
def inScriptFolder(f):
return os.path.join(os.path.dirname(os.path.realpath(__file__)),f)
class Stack(deque):
def push(self, *args):
for arg in args:
self.append(arg)
def pop(self, n=0):
if n > 0:
ret = []
for i in range(n):
ret.append(super().pop())
return tuple(ret)
else:
return super().pop()
def remove(self,value):
try:
super().remove(value)
return True
except:
return False
def asList(self):
return list(self)
class Map(dict):
"""
Example:
m = Map({'first_name': 'Eduardo'}, last_name='Pool', age=24, sports=['Soccer'])
"""
def __init__(self, *args, **kwargs):
super(Map, self).__init__(*args, **kwargs)
for arg in args:
if isinstance(arg, dict):
for k, v in arg.items():
self[k] = v
if kwargs:
for k, v in kwargs.items():
self[k] = v
def __getattr__(self, attr):
return self.get(attr)
def __setattr__(self, key, value):
self.__setitem__(key, value)
def __setitem__(self, key, value):
super(Map, self).__setitem__(key, value)
self.__dict__.update({key: value})
def __delattr__(self, item):
self.__delitem__(item)
def __delitem__(self, key):
super(Map, self).__delitem__(key)
del self.__dict__[key]
class Assembler():
cfg = False
currentFolder = None
currentFilename = None
initialFolder = None
initialFilename = None
hideOutputLine = False
suppressError = False
currentTextMap = 'default'
textMap = {}
errorLinePos = False
expected = False
expectedWait = False
warnings = 0
palette = defaultPalette[:]
currentPalette = [0x0f,0x01,0x11,0x30]
stripHeader = False
namespace = Stack([''])
#quotes = ('"""','"',"'")
quotes = False
hidePrefix = '__hide__'
caseSensitive = False
Sprite8x16 = False
echoLine = False
localPrefix = []
lastLabel = ''
localLabels = Map()
localLabelKeys = {}
line = ''
lineNumber = 0
fileLineNumber = 0
error = False # used to determine if exit code 3 is needed
errorText = ''
memcfg = False
insert = False
gg = False
outputFilename = False
printFilename = False
listFilename = False
bankData = {}
commentBlock = 0
shatter = False
pcStack = False
baseStack = False
nesRegisters = Map(
PPUCTRL = 0x2000, PPUMASK = 0x2001, PPUSTATUS = 0x2002,
OAMADDR = 0x2003, OAMDATA = 0x2004, PPUSCROLL = 0x2005,
PPUADDR = 0x2006, PPUDATA = 0x2007, OAMDMA = 0x4014,
SQ1VOL = 0x4000, SQ1SWEEP = 0x4001, SQ1LO = 0x4002,
SQ1HI = 0x4003,
SQ2VOL = 0x4004, SQ2SWEEP = 0x4005, SQ2LO = 0x4006,
SQ2HI = 0x4007,
TRILINEAR = 0x4008, TRILO = 0x400A, TRIHI = 0x400B,
NOISEVOL = 0x400C, NOISELO = 0x400E, NOISEHI = 0x400F,
DMCFREQ = 0x4010, DMCRAW = 0x4011, DMCSTART = 0x4012,
DMCLEN = 0x4013,
APUSTATUS = 0x4015, APUFRAME = 0x4017,
JOY = 0x4016, JOY1 = 0x4016, JOY2 = 0x4017,
)
nesRegisters = Map({x.lower():y for x,y in nesRegisters.items()})
def get(self, prop):
return getattr(self, prop)
def __init__(self):
pass
def dummy(self):
pass
def printError(self, errorText = '', line = ''):
if not errorText:
errorText = self.errorText
print(line)
if self.errorLinePos:
print(' '*self.errorLinePos+'^')
print('*** {}'.format(errorText))
print(' {}\n'.format(self.currentFilename))
self.errorLinePos = False
def lower(self, txt):
if self.caseSensitive:
return txt
return txt.lower()
def isString(self, text):
for q in self.quotes:
if text.startswith(q) and text.endswith(q):
return True
def stripQuotes(self, text):
for q in self.quotes:
if text.startswith(q) and text.endswith(q):
return text[len(q):-len(q)]
return text
def stripComments(self, text=''):
# inside a comment block, so just check for block close indicators
if self.commentBlock:
pos = -1
for c in self.commentBlockClose:
if c in text:
if pos == -1:
pos = text.find(c) + len(c)
else:
pos = min(pos, text.find(c) + len(c))
if pos == -1:
# inside a block comment so return empty string
return ""
else:
self.commentBlock -= 1
return self.stripComments(text[pos:].strip())
commentSep = self.commentSep + self.commentBlockOpen
# check for any quotes or comments to handle
# if none found, we're done; return text
if not any(q in text for q in self.quotes):
if not any(sep in text for sep in commentSep):
return text
qIndex = -1
q = ''
for quote in self.quotes:
i = text.find(quote)
if i != -1:
# conditions are:
# 1. first quote found
# 2. quote found at lesser position in string
# 3. quote found at same position in string (handles " vs """ etc)
if (qIndex == -1) or (i < qIndex) or ((i == qIndex) and len(quote) > len(q)):
qIndex = i
q = quote
# check if comment comes before first string
cIndex = len(text)
cType = False
for sep in commentSep:
i = text.find(sep)
if i !=-1:
if (qIndex == -1) and (i < cIndex):
# no quotes found, just mark comment start
cType = sep
cIndex = i
elif (i < qIndex) and (i < cIndex):
# comments found before quotes, mark start
cType = sep
cIndex = i
# no need for more tokenization; trim and exit
if cIndex < len(text):
text = text[:cIndex]
if cType in self.commentBlockOpen:
self.commentBlock += 1
print('comment block open')
return text
# find end of string
i = text.find(q, qIndex + len(q))
if i != -1:
i = i + len(q)
text = text[:i] + self.stripComments(text[i:])
return text
def tokenize(self, text='', tokens=[], splitter=','):
tokens = tokens or [text]
txt = tokens[-1]
if not any(q in txt for q in self.quotes):
if not any(q in txt for q in "[]"):
return tokens[:-1] + [x.strip() for x in txt.split(splitter)]
q = False
for quote in self.quotes:
if txt.startswith(quote):
q = quote
break
if txt.startswith('['):
q = ']'
n1=0
if q:
n1 = txt.find(q,len(q))+len(q)
n2 = txt.find(splitter,n1)
if n2==-1:
return tokens
left = txt[:n2].strip()
right = txt[n2+1:].strip()
tokens = tokens[:-1] + [left, right]
return self.tokenize(text, tokens)
def mapText(self, text):
#print("Mapping text:", text)
textMap = self.textMap.get(self.currentTextMap, {})
# try:
# ret = [textMap.get(x, ord(x)) for x in text]
# except:
# print('bad textmap data')
# ret = [0 for x in text]
# return ret
ret = [textMap.get(x, ord(x)) for x in text]
return ret
def setTextMap(self, name):
self.currentTextMap = name
def getTextMap(self):
return self.currentTextMap
def clearTextMap(self, name=False, all=False):
if all:
self.currentTextMap = 'default'
self.textMap = {}
if not name:
name = self.currentTextMap
if name in self.textMap:
self.textMap.pop(name)
def setTextMapData(self, chars, mapTo):
textMap = self.textMap.get(self.currentTextMap, {})
textMap.update(dict(zip(chars,bytearray.fromhex(mapTo))))
self.textMap[self.currentTextMap] = textMap
def loadTbl(self, filename=False):
filename = self.findFile(filename)
if filename:
try:
file = open(filename, "rb")
except:
self.errorHint = 'could not open file.'
return False
tbl=['','']
for line in file.read().decode('utf-8-sig').splitlines():
l = line.split('=')
if len(l[0])==1 and len(l[1])==2:
l = list(reversed(l))
if len(l[0])==2 and len(l[1])==1:
tbl[1]+=l[0]
tbl[0]+=l[1]
elif line == '':
pass
else:
self.errorHint = 'Invalid tbl entry'
return False
self.setTextMapData(tbl[0],tbl[1])
return True
else:
self.errorHint = 'file not found'
return False
def loadPalette(self, filename=False):
if filename:
filename = self.findFile(filename)
if filename:
try:
file = open(filename, "rb")
except:
self.errorHint = 'could not open file.'
return False
p = list(file.read())
if len(p) != 192:
self.errorHint = 'palette file size must be 192 bytes'
return False
p = [p[i:i + 3] for i in range(0, len(p), 3)]
self.palette = p
else:
self.errorHint = 'file not found'
return False
else:
self.palette = defaultPalette[:]
return self.palette
def findFile(self, filename):
if not filename:
return False
# Search for files in this order:
# Exact match
# Relative to current script folder
# Relative to initial script folder
# Relative to current working folder
# Relative to top level of initial script folder
# Relative to executable folder
files = [
filename,
os.path.join(self.currentFolder,filename),
os.path.join(self.initialFolder,filename),
os.path.join(os.getcwd(),filename),
os.path.join(str(pathlib.Path(*pathlib.Path(self.initialFolder).parts[:1])),filename),
os.path.join(os.path.dirname(os.path.realpath(__file__)),filename),
]
files = [x.replace('\\\\','\\') for x in files]
for f in files:
if os.path.isfile(f): return f
return False
assembler = Assembler()
operations = {
# '-':operator.sub,
# '+':operator.add,
'/':operator.truediv,
'&':operator.and_,
'^':operator.xor,
'~':operator.invert,
'|':operator.or_,
'**':operator.pow,
'<<':operator.lshift,
'>>':operator.rshift,
'%':operator.mod,
'*':operator.mul,
}
directives = [
'org','base','pad','fillto','align','fill','fillvalue','fillbyte','padbyte',
'include','include?','incsrc','require','includeall','incbin','bin',
'db','dw','byte','byt','word','hex','dc.b','dc.w',
'dsb','dsw','ds.b','ds.w','dl','dh','res',
'enum','ende','endenum',
'print','warning','error','printtofile',
'setincludefolder','setcurrentfile',
'macro','endm','endmacro',
'if','ifdef','ifndef','else','elseif','endif','iffileexist','iffile',
'arch','table','loadtable','cleartable','mapdb','clampdb',
'index','mem','bank','lastbank','banksize','chrsize','header','noheader','stripheader',
'define', '_find','absorg',
'seed','outputfile','listfile','textmap','text','insert','delete','truncate','printfile',
'inesprg','ineschr','inesmir','inesmap','inesbattery','inesfourscreen',
'inesworkram','inessaveram','ines2',
'orgpad', 'padorg', 'quit','incchr','chr','setpalette','loadpalette',
'rept','endr','endrept','sprite8x16','export','diff','diff2',
'assemble', 'exportchr', 'ips','makeips', 'gg','echo','function','endf', 'endfunction',
'return','namespace','break','expected',
'findtext','lastpass', 'endoffunction', '_wipe',
'loadld65cfg','loadld65cfg?','segment',
'start','end','exportmap','importmap','_test','_shatterhand_import',
'pushpc','pullpc','pushbase','pullbase',
]
filters = [
'shuffle','getbyte','getbytes','getword','choose',
'format','random','range','textmap',
'evalvar','pop','astext','len',
'fileexist', 'nfileexist','py',
'concat','coalesce',
'namespace',
]
def clamp(n, smallest, largest): return max(smallest, min(n, largest))
autoFilters = {
'floor':math.floor,
'ceil':math.ceil,
'clamp':clamp,
}
filters = filters + list(autoFilters.keys())
asm=[
Map(opcode = 'adc', mode = 'Immediate', byte = 105, length = 2),
Map(opcode = 'adc', mode = 'Zero Page', byte = 101, length = 2),
Map(opcode = 'adc', mode = 'Zero Page, X', byte = 117, length = 2),
Map(opcode = 'adc', mode = 'Absolute', byte = 109, length = 3),
Map(opcode = 'adc', mode = 'Absolute, X', byte = 125, length = 3),
Map(opcode = 'adc', mode = 'Absolute, Y', byte = 121, length = 3),
Map(opcode = 'adc', mode = '(Indirect, X)', byte = 97, length = 2),
Map(opcode = 'adc', mode = '(Indirect), Y', byte = 113, length = 2),
Map(opcode = 'and', mode = 'Immediate', byte = 41, length = 2),
Map(opcode = 'and', mode = 'Zero Page', byte = 37, length = 2),
Map(opcode = 'and', mode = 'Zero Page, X', byte = 53, length = 2),
Map(opcode = 'and', mode = 'Absolute', byte = 45, length = 3),
Map(opcode = 'and', mode = 'Absolute, X', byte = 61, length = 3),
Map(opcode = 'and', mode = 'Absolute, Y', byte = 57, length = 3),
Map(opcode = 'and', mode = '(Indirect, X)', byte = 33, length = 2),
Map(opcode = 'and', mode = '(Indirect), Y', byte = 49, length = 2),
Map(opcode = 'asl', mode = 'Accumulator', byte = 10, length = 1),
Map(opcode = 'asl', mode = 'Zero Page', byte = 6, length = 2),
Map(opcode = 'asl', mode = 'Zero Page, X', byte = 22, length = 2),
Map(opcode = 'asl', mode = 'Absolute', byte = 14, length = 3),
Map(opcode = 'asl', mode = 'Absolute, X', byte = 30, length = 3),
Map(opcode = 'bcc', mode = 'Relative', byte = 144, length = 2),
Map(opcode = 'bcs', mode = 'Relative', byte = 176, length = 2),
Map(opcode = 'beq', mode = 'Relative', byte = 240, length = 2),
Map(opcode = 'bit', mode = 'Zero Page', byte = 36, length = 2),
Map(opcode = 'bit', mode = 'Absolute', byte = 44, length = 3),
Map(opcode = 'bmi', mode = 'Relative', byte = 48, length = 2),
Map(opcode = 'bne', mode = 'Relative', byte = 208, length = 2),
Map(opcode = 'bpl', mode = 'Relative', byte = 16, length = 2),
Map(opcode = 'brk', mode = 'Implied', byte = 0, length = 1),
Map(opcode = 'bvc', mode = 'Relative', byte = 80, length = 2),
Map(opcode = 'bvs', mode = 'Relative', byte = 112, length = 2),
Map(opcode = 'clc', mode = 'Implied', byte = 24, length = 1),
Map(opcode = 'cld', mode = 'Implied', byte = 216, length = 1),
Map(opcode = 'cli', mode = 'Implied', byte = 88, length = 1),
Map(opcode = 'clv', mode = 'Implied', byte = 184, length = 1),
Map(opcode = 'cmp', mode = 'Immediate', byte = 201, length = 2),
Map(opcode = 'cmp', mode = 'Zero Page', byte = 197, length = 2),
Map(opcode = 'cmp', mode = 'Zero Page, X', byte = 213, length = 2),
Map(opcode = 'cmp', mode = 'Absolute', byte = 205, length = 3),
Map(opcode = 'cmp', mode = 'Absolute, X', byte = 221, length = 3),
Map(opcode = 'cmp', mode = 'Absolute, Y', byte = 217, length = 3),
Map(opcode = 'cmp', mode = '(Indirect, X)', byte = 193, length = 2),
Map(opcode = 'cmp', mode = '(Indirect), Y', byte = 209, length = 2),
Map(opcode = 'cpx', mode = 'Immediate', byte = 224, length = 2),
Map(opcode = 'cpx', mode = 'Zero Page', byte = 228, length = 2),
Map(opcode = 'cpx', mode = 'Absolute', byte = 236, length = 3),
Map(opcode = 'cpy', mode = 'Immediate', byte = 192, length = 2),
Map(opcode = 'cpy', mode = 'Zero Page', byte = 196, length = 2),
Map(opcode = 'cpy', mode = 'Absolute', byte = 204, length = 3),
Map(opcode = 'dec', mode = 'Zero Page', byte = 198, length = 2),
Map(opcode = 'dec', mode = 'Zero Page, X', byte = 214, length = 2),
Map(opcode = 'dec', mode = 'Absolute', byte = 206, length = 3),
Map(opcode = 'dec', mode = 'Absolute, X', byte = 222, length = 3),
Map(opcode = 'dex', mode = 'Implied', byte = 202, length = 1),
Map(opcode = 'dey', mode = 'Implied', byte = 136, length = 1),
Map(opcode = 'eor', mode = 'Immediate', byte = 73, length = 2),
Map(opcode = 'eor', mode = 'Zero Page', byte = 69, length = 2),
Map(opcode = 'eor', mode = 'Zero Page, X', byte = 85, length = 2),
Map(opcode = 'eor', mode = 'Absolute', byte = 77, length = 3),
Map(opcode = 'eor', mode = 'Absolute, X', byte = 93, length = 3),
Map(opcode = 'eor', mode = 'Absolute, Y', byte = 89, length = 3),
Map(opcode = 'eor', mode = '(Indirect, X)', byte = 65, length = 2),
Map(opcode = 'eor', mode = '(Indirect), Y', byte = 81, length = 2),
Map(opcode = 'inc', mode = 'Zero Page', byte = 230, length = 2),
Map(opcode = 'inc', mode = 'Zero Page, X', byte = 246, length = 2),
Map(opcode = 'inc', mode = 'Absolute', byte = 238, length = 3),
Map(opcode = 'inc', mode = 'Absolute, X', byte = 254, length = 3),
Map(opcode = 'inx', mode = 'Implied', byte = 232, length = 1),
Map(opcode = 'iny', mode = 'Implied', byte = 200, length = 1),
Map(opcode = 'jmp', mode = 'Indirect', byte = 108, length = 3),
Map(opcode = 'jmp', mode = 'Absolute', byte = 76, length = 3),
Map(opcode = 'jsr', mode = 'Absolute', byte = 32, length = 3),
Map(opcode = 'lda', mode = 'Immediate', byte = 169, length = 2),
Map(opcode = 'lda', mode = 'Zero Page', byte = 165, length = 2),
Map(opcode = 'lda', mode = 'Zero Page, X', byte = 181, length = 2),
Map(opcode = 'lda', mode = 'Absolute', byte = 173, length = 3),
Map(opcode = 'lda', mode = 'Absolute, X', byte = 189, length = 3),
Map(opcode = 'lda', mode = 'Absolute, Y', byte = 185, length = 3),
Map(opcode = 'lda', mode = '(Indirect, X)', byte = 161, length = 2),
Map(opcode = 'lda', mode = '(Indirect), Y', byte = 177, length = 2),
Map(opcode = 'ldx', mode = 'Zero Page', byte = 166, length = 2),
Map(opcode = 'ldx', mode = 'Zero Page, Y', byte = 182, length = 2),
Map(opcode = 'ldx', mode = 'Absolute', byte = 174, length = 3),
Map(opcode = 'ldx', mode = 'Absolute, Y', byte = 190, length = 3),
Map(opcode = 'ldx', mode = 'Immediate', byte = 162, length = 2),
Map(opcode = 'ldy', mode = 'Immediate', byte = 160, length = 2),
Map(opcode = 'ldy', mode = 'Zero Page', byte = 164, length = 2),
Map(opcode = 'ldy', mode = 'Zero Page, X', byte = 180, length = 2),
Map(opcode = 'ldy', mode = 'Absolute', byte = 172, length = 3),
Map(opcode = 'ldy', mode = 'Absolute, X', byte = 188, length = 3),
Map(opcode = 'lsr', mode = 'Accumulator', byte = 74, length = 1),
Map(opcode = 'lsr', mode = 'Zero Page', byte = 70, length = 2),
Map(opcode = 'lsr', mode = 'Zero Page, X', byte = 86, length = 2),
Map(opcode = 'lsr', mode = 'Absolute', byte = 78, length = 3),
Map(opcode = 'lsr', mode = 'Absolute, X', byte = 94, length = 3),
Map(opcode = 'nop', mode = 'Implied', byte = 234, length = 1),
Map(opcode = 'ora', mode = 'Immediate', byte = 9, length = 2),
Map(opcode = 'ora', mode = 'Zero Page', byte = 5, length = 2),
Map(opcode = 'ora', mode = 'Zero Page, X', byte = 21, length = 2),
Map(opcode = 'ora', mode = 'Absolute', byte = 13, length = 3),
Map(opcode = 'ora', mode = 'Absolute, X', byte = 29, length = 3),
Map(opcode = 'ora', mode = 'Absolute, Y', byte = 25, length = 3),
Map(opcode = 'ora', mode = '(Indirect, X)', byte = 1, length = 2),
Map(opcode = 'ora', mode = '(Indirect), Y', byte = 17, length = 2),
Map(opcode = 'pha', mode = 'Implied', byte = 72, length = 1),
Map(opcode = 'php', mode = 'Implied', byte = 8, length = 1),
Map(opcode = 'pla', mode = 'Implied', byte = 104, length = 1),
Map(opcode = 'plp', mode = 'Implied', byte = 40, length = 1),
Map(opcode = 'rol', mode = 'Accumulator', byte = 42, length = 1),
Map(opcode = 'rol', mode = 'Zero Page', byte = 38, length = 2),
Map(opcode = 'rol', mode = 'Zero Page, X', byte = 54, length = 2),
Map(opcode = 'rol', mode = 'Absolute', byte = 46, length = 3),
Map(opcode = 'rol', mode = 'Absolute, X', byte = 62, length = 3),
Map(opcode = 'ror', mode = 'Accumulator', byte = 106, length = 1),
Map(opcode = 'ror', mode = 'Zero Page', byte = 102, length = 2),
Map(opcode = 'ror', mode = 'Zero Page, X', byte = 118, length = 2),
Map(opcode = 'ror', mode = 'Absolute', byte = 110, length = 3),
Map(opcode = 'ror', mode = 'Absolute, X', byte = 126, length = 3),
Map(opcode = 'rti', mode = 'Implied', byte = 64, length = 1),
Map(opcode = 'rts', mode = 'Implied', byte = 96, length = 1),
Map(opcode = 'sbc', mode = 'Immediate', byte = 233, length = 2),
Map(opcode = 'sbc', mode = 'Zero Page', byte = 229, length = 2),
Map(opcode = 'sbc', mode = 'Zero Page, X', byte = 245, length = 2),
Map(opcode = 'sbc', mode = 'Absolute', byte = 237, length = 3),
Map(opcode = 'sbc', mode = 'Absolute, X', byte = 253, length = 3),
Map(opcode = 'sbc', mode = 'Absolute, Y', byte = 249, length = 3),
Map(opcode = 'sbc', mode = '(Indirect, X)', byte = 225, length = 2),
Map(opcode = 'sbc', mode = '(Indirect), Y', byte = 241, length = 2),
Map(opcode = 'sec', mode = 'Implied', byte = 56, length = 1),
Map(opcode = 'sed', mode = 'Implied', byte = 248, length = 1),
Map(opcode = 'sei', mode = 'Implied', byte = 120, length = 1),
Map(opcode = 'sta', mode = 'Zero Page', byte = 133, length = 2),
Map(opcode = 'sta', mode = 'Zero Page, X', byte = 149, length = 2),
Map(opcode = 'sta', mode = 'Absolute', byte = 141, length = 3),
Map(opcode = 'sta', mode = 'Absolute, X', byte = 157, length = 3),
Map(opcode = 'sta', mode = 'Absolute, Y', byte = 153, length = 3),
Map(opcode = 'sta', mode = '(Indirect, X)', byte = 129, length = 2),
Map(opcode = 'sta', mode = '(Indirect), Y', byte = 145, length = 2),
Map(opcode = 'stx', mode = 'Zero Page', byte = 134, length = 2),
Map(opcode = 'stx', mode = 'Zero Page, Y', byte = 150, length = 2),
Map(opcode = 'stx', mode = 'Absolute', byte = 142, length = 3),
Map(opcode = 'sty', mode = 'Zero Page', byte = 132, length = 2),
Map(opcode = 'sty', mode = 'Zero Page, X', byte = 148, length = 2),
Map(opcode = 'sty', mode = 'Absolute', byte = 140, length = 3),
Map(opcode = 'tax', mode = 'Implied', byte = 170, length = 1),
Map(opcode = 'tay', mode = 'Implied', byte = 168, length = 1),
Map(opcode = 'tsx', mode = 'Implied', byte = 186, length = 1),
Map(opcode = 'txa', mode = 'Implied', byte = 138, length = 1),
Map(opcode = 'txs', mode = 'Implied', byte = 154, length = 1),
Map(opcode = 'tya', mode = 'Implied', byte = 152, length = 1),
]
architectures = ['nes.cpu','6502']
# Converting to dictionary removes duplicates
opcodes = list(dict.fromkeys([x.opcode for x in asm]))
opcodes2 = [
'lda','ldx','ldy',
'sta','stx','sty',
'and','asl','bit','eor','lsr','ora','rol','ror',
'adc','dec','dex','dey','inc','inx','iny','sbc',
'cmp','cpx','cpy',
'jmp',
]
opcodes2 = [x+'.b' for x in opcodes2]+[x+'.w' for x in opcodes2]
implied = [x.opcode for x in asm if x.mode=='Implied']
accumulator = [x.opcode for x in asm if x.mode=="Accumulator"]
ifDirectives = ['if','endif','else','elseif','ifdef','ifndef','iffileexist','iffile']
mergeList = lambda a,b: [(a[i], b[i]) for i in range(min(len(a),len(b)))]
makeHex = lambda x: '$'+x.to_bytes(((x.bit_length()|1 + 7) // 8),"big").hex()
superglobals = [
'return'
]
specialSymbols = [
'sdasm','bank','banksize','chrsize','randbyte','randword','fileoffset',
'prgbanks','chrbanks','lastbank','lastchr','mapper','binfile','namespace',
'vectornmi','vectorreset','vectorirq','warnings',
]
timeSymbols = ['year','month','day','hour','minute','second']
specialSymbols+= timeSymbols
specialSymbols+= [x.lower() for x in assembler.nesRegisters.keys()]
def assemble(filename, outputFilename = 'output.bin', listFilename = False, configFile=False, fileData=False, binFile=False, symbolsFile=False, quiet=False, defineSymbol=''):
assembler.error = False
#quiet=True
if not configFile:
if frozen:
configFile = 'sdasm.ini'
else:
configFile = inScriptFolder('config.ini')
cfg = False
# create our config parser
cfg = Cfg(configFile)
# read config file if it exists
cfg.load()
# number of bytes to show when generating list
cfg.setDefault('main', 'list_nBytes', 8)
cfg.setDefault('main', 'metaCommandPrefix', ';!,//!,;//!')
cfg.setDefault('main', 'comment', ';,//')
cfg.setDefault('main', 'commentBlockOpen', '/*')
cfg.setDefault('main', 'commentBlockClose', '*/')
cfg.setDefault('main', 'nestedComments', True)
cfg.setDefault('main', 'fillValue', '$00')
cfg.setDefault('main', 'localPrefix', '@')
cfg.setDefault('main', 'debug', False)
cfg.setDefault('main', 'varOpen', '{')
cfg.setDefault('main', 'varClose', '}')
cfg.setDefault('main', 'labelSuffix', ':')
cfg.setDefault('main', 'namespaceSymbol', '.')
cfg.setDefault('main', 'orgPad', 0)
cfg.setDefault('main', 'padOrg', 0)
cfg.setDefault('main', 'mapdb', False)
cfg.setDefault('main', 'lineSep', '')
cfg.setDefault('main', 'clampdb', False)
cfg.setDefault('main', 'caseSensitive', False)
cfg.setDefault('main', 'lineContinue', '\\')
cfg.setDefault('main', 'lineContinueComma', True)
cfg.setDefault('main', 'quotes', '\',","""')
cfg.setDefault('main', 'suppressErrorPrefix', '-E-,-e-')
cfg.setDefault('main', 'floorDiv', True)
cfg.setDefault('main', 'xkasplusbranch', False)
cfg.setDefault('main', 'showFileOffsetInListFile', True)
cfg.setDefault('main', 'showBankInListFile', False)
cfg.setDefault('main', 'fullTraceback', False)
cfg.setDefault('main', 'loadld65cfg', True)
cfg.setDefault('main', 'rememberBankAddress', False)