-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtinkasm.py
2565 lines (1842 loc) · 77.8 KB
/
tinkasm.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
# A Tinkerer's Assembler for the 6502/65c02/65816 in Forth
# Scot W. Stevenson <[email protected]>
# First version: 24. Sep 2015
# This version: 07. Feb 2019
# This program 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 <http://www.gnu.org/licenses/>.
"""TinkAsm is a multi-pass assembler for the 6502/65c02/65816 MPUs.
It is intended to be easy to modify by hobbyists without advanced knowledge
of how lexing and parsing works -- so they can "tinker" -- and is
intentionally written in a "primitive" style of Python.
"""
### SETUP ###
import argparse
import copy
import operator
import re
import string
import sys
import time
import timeit
from rpnmath.rpnengine import engine
from common.common import convert_number
# Check for correct version of Python
if sys.version_info.major != 3:
print("FATAL: Python 3 required. Aborting.")
sys.exit(1)
# Initialize various counts. Some of these are just for general data collection
n_comment_lines = 0 # How many full-line comments
n_empty_lines = 0 # How many lines where only whitespace
n_external_files = 0 # How many external files were loaded
n_instructions = 0 # How many instruction lines
n_invocations = 0 # How many macros were expanded
n_passes = 0 # Number of passes during processing
n_steps = 0 # Number of steps during processing
n_switches = 0 # How many 8/16 bit register switches on 65816
n_warnings = 0 # How many warnings were generated
code_size = 0 # Final size in bytes
### ARGUMENTS ###
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--input', dest='source', required=True,\
help='Assembler source code file (required)')
parser.add_argument('-ir', '--intermediate-representation',\
action='store_true', dest='ir', default=False,\
help='Save Intermediate Representation of assembly data (default TINK.IR)')
parser.add_argument('-o', '--output', dest='output',\
help='Binary output file (default TINK.BIN)', default='tink.bin')
parser.add_argument('-v', '--verbose',\
help='Display additional information', action='store_true')
parser.add_argument('-l', '--listing', action='store_true',\
help='Create listing file (default TINK.LST)')
parser.add_argument('-x', '--hexdump', action='store_true',\
help='Create ASCII hexdump listing file (default TINK.HEX)')
parser.add_argument('-s28', action='store_true',\
help='Create S28 format file from binary (default TINK.S28)')
parser.add_argument('-p', '--print', action='store_true', default=False,\
help='Print listing to screen at end')
parser.add_argument('-w', '--warnings', default=True,\
help='Disable warnings (default: print them)', action='store_false')
args = parser.parse_args()
### BASIC OUTPUT FUNCTIONS ###
def hexstr(n, i):
"""Given an integer i, return a hex number with n digits as a string that
has the '0x' portion stripped out and is limited to 24 bit (to correctly
handle the negative numbers) and is n characters wide.
"""
try:
fmtstr = '{0:0'+str(n)+'x}'
return fmtstr.format(i & 0x0ffffff)
except TypeError as err:
fatal(line, 'TypeError in hexstr for "{i}": {err}')
def fatal(line, s):
"""Abort program because of fatal error during assembly.
"""
if line.sec_ln == 0:
print(f'FATAL ERROR line {line.ln} - {s}')
else:
print(f'FATAL ERROR line {line.ln}:{line.sec_ln} - {s}')
sys.exit(1)
def verbose(s):
"""Print information string given if --verbose flag was set. Later
expand this by the option of priting to a log file instead.
"""
if args.verbose:
print(s)
def warning(s):
"""If program called with -w or --warnings, print a warning string.
"""
global n_warnings
n_warnings += 1
if args.warnings:
print(f'WARNING: {s}')
### CONSTANTS ###
TITLE_STRING = \
"""A Tinkerer's Assembler for the 6502/65c02/65816
Version BETA 07. Feb 2019
Copyright 2015-2019 Scot W. Stevenson <[email protected]>
This program comes with ABSOLUTELY NO WARRANTY
"""
COMMENT_MARKER = ';' # Comment marker, default is ";"
CURRENT = '.*' # Current location counter, default is ".*"
ASSIGNMENT = '.equ' # Assignment directive, default is ".equ"
LOCAL_LABEL = '@' # Marker for anonymous labels, default is "@"
LABEL_MARKER = ':' # Postfix that defines a word as a label if first in line
LEFTMATH = '[' # Opening bracket for Python math terms
RIGHTMATH = ']' # Closing bracket for Python math terms
INDENT = ' '*8 # Indent in whitespace for formatting
LC0 = 0 # Start address of code ("location counter")
LCi = 0 # Index to where we are in code from the LC0
HEX_FILE = 'tink.hex' # Default name of hexdump file
LIST_FILE = 'tink.lst' # Default name of listing file
IR_FILE = 'tink.ir' # Default name of IR file
S28_FILE = 'tink.s28' # Default name of S28 file
# We store the general lists here, those specific to one processor type are put
# in the relevant passes.
SUPPORTED_MPUS = ['6502', '65c02', '65816']
DATA_DIRECTIVES = ['.byte', '.word', '.long']
symbol_table = {}
anon_labels = []
# Line types. Start off with UNKNOWN, then are later replaced by real type as
# discovered or added. CONTROL is added internally by the assembler for various
# control structures
UNKNOWN = ' ' # Pre-processing default
COMMENT = 'cmt' # Whole-line comments, not inline
DIRECTIVE = 'dir'
INSTRUCTION = 'ins'
LABEL = 'lbl'
CONTROL = 'ctl' # Used for lines added by the assembler
WHITESPACE = 'wsp' # Used for whole-line whitespace
# Line status. Starts with UNTOUCHED, then MODIFIED if changes are made, and
# then DONE if line does not need any more work.
UNTOUCHED = ' '
MODIFIED = 'work'
DONE = 'DONE'
# CLASSES
class CodeLine:
def __init__(self, rawstring, ln, sec_ln=0):
self.raw = rawstring # Original line as a string
self.ln = ln # Primary line number (in source file)
self.sec_ln = sec_ln # Secondary line number for expanded lines
self.status = UNTOUCHED # Flag if line has been processed
self.type = UNKNOWN # Type of line, starts UNKNOWN, ends DATA
self.action = '' # First word of instruction or directive
self.parameters = '' # Parameter(s) of instruction or directive
self.address = 0 # Address where line data begins (16/24 bit)
self.il_comment = '' # Storage area for any inline comments
self.size = 0 # Size of instruction in bytes
self.bytes = '' # Bytes for actual, final assembly
self.mode = 'em' # For 65816: default mode (emulated)
self.a_width = 8 # For 65816: defalt width of A register
self.xy_width = 8 # For 65816: default width of XY registers
# List of all directives. Note the anonymous label character is not included
# because this is used to keep the user from using these words as labels
DIRECTIVES = ['.!a8', '.!a16', '.a8', '.a16', '.origin', '.axy8', '.axy16',\
'.end', ASSIGNMENT, '.byte', '.word', '.long', '.advance', '.skip',\
'.native', '.emulated', '.mpu', '.save',\
'.!xy8', '.!xy16', '.xy8', '.xy16', COMMENT_MARKER,\
'.lsb', '.msb', '.bank', '.lshift', '.rshift', '.invert',\
'.and', '.or', '.xor', CURRENT, '.macro', '.endmacro', '.invoke',\
'.include', '.!native', '.!emulated', LEFTMATH, RIGHTMATH]
### HELPER FUNCTIONS ###
def lsb(line, n):
"""Return Least Significant Byte of a number"""
try:
t = n & 0xff
except TypeError:
fatal(line, f"Can't convert '{n}' to lsb")
else:
return t
def msb(line, n):
"""Return Most Significant Byte of a number"""
try:
t = (n & 0xff00) >> 8
except TypeError:
fatal(line, f"Can't convert '{n}' to msb")
else:
return t
def bank(line, n):
"""Return Bank Byte of a number"""
try:
t = (n & 0xff0000) >> 16
except TypeError:
fatal(line, f"Can't convert '{n}' to bank")
else:
return t
MODIFIERS = {'.lsb': lsb, '.msb': msb, '.bank': bank}
def little_endian_16(line, n):
"""Given a number, return a tuple with two bytes in correct format"""
return lsb(line, n), msb(line, n)
def little_endian_24(line, n):
"""Given a number, return a tuple with three bytes in correct format"""
return lsb(line, n), msb(line, n), bank(line, n)
def string2bytestring(s):
"""Given a string marked with quotation marks, return a string that is a
comma-separated list of their hex ASCII values. Assumes that there is one
and only one string in the line that is delimited by quotation marks.
Example: "abc" -> "61, 62, 63"
"""
# We slice one character off both ends because those are the quotation marks
t = ' '.join([hexstr(2, ord(c))+',' for c in s[1:-1]])
# We don't want to add a comma to the end of the list because either the
# string was at the end of the line or there is already a comma present
# from the listing
return t[:-1]
def do_math(s):
"""Given a payload string with math term inside, replace the math term by
a string representation of the number by the math engine. What is before
and after the math term is conserved. Returns a string representation of
a decimal number
"""
# Save the parts that are left and right of the math term
w1 = s.split(LEFTMATH, 1)
pre_math = w1[0]
w2 = w1[1].split(RIGHTMATH, 1)
post_math = w2[1]
# The math engine requires some filtering
ts = w2[0].split()
rs = ''
for t in ts:
# See if it's a number, converting it while we're at it
f_num, opr = convert_number(t)
if f_num:
rs = rs+' '+str(opr)
continue
# Okay, maybe it is a known symbol
try:
s = symbol_table[t.lower()]
except KeyError:
rs = rs+' '+t
else:
rs = rs+' '+str(s)
# We should be good. Run the term through the RPN engine.
r, ok = engine(rs)
if not ok:
fatal(line, f'Math engine failed on term: "{w2[0].strip()}"')
return pre_math + str(r) + post_math
def vet_newsymbol(s):
"""Given a word that the user wants to define as a new symbol, make sure
that is is legal. Does not return anything if okay, jumps to fatal error
if not.
"""
# We don't allow using directives as symbols because that gets very
# confusing really fast
if s in DIRECTIVES:
fatal(line, 'Directive "{s}" cannot be redefined as a symbol')
# We don't allow using mnemonics as symbols because that screws up other
# stuff and is really weird anyway
if s in mnemonics.keys():
fatal(line, f'Mnemonic "{s}" cannot be redefined as a symbol')
# We don't allow redefining existing symbols, this catches various errors
if s in symbol_table.keys():
fatal(line, f'Symbol "{s}" already defined')
def replace_symbols(src):
"""Given the list of CodeLine elements, replace the symbols we know.
Will find symbols in math terms, but not in .BYTE etc data
directives.
"""
sr_count = 0
for line in src:
if (line.status == DONE) or (line.type == LABEL):
continue
# We need to go word-by-word because somebody might be defining .byte
# data as symbols
wc = []
ws = line.parameters.split()
# Spliting the lines returns whatever is separated by whitespace. In
# data directives such as .BYTE, however, this will return the symbol
# with a comma tacked on. We take care of those cases separately
for w in ws:
try:
# We don't define the number of digits because we have no idea
# what the number they represent are supposed to be
w = str(symbol_table[w])
except KeyError:
pass
else:
sr_count += 1
line.status = MODIFIED
finally:
wc.append(w)
line.parameters = ' '.join(wc)
verbose(f'PASS REPLACED: Replaced {sr_count} known symbol(s) with known values')
def dump_symbol_table(st, s=""):
"""Print Symbol Table to screen"""
print('Symbol Table', s)
if len(st) <= 0:
print(' - (symbol table is empty)\n')
return
# Find longest symbol name in table
max_sym_len = max([len(k) for k in st.keys()])
for v in sorted(st):
print('- {0:{width}} : {1:06x}'.format(v, st[v], width=max_sym_len))
def convert_term(line, s):
"""Given the line number and a string that can be a number (in various
formats), a symbol (that must already be known), a modifier (such as
'.lsb'), a math term (such as '[ 1 1 + ]') or a combination of modifier
and math term ('.lsb [ 1 1 + ]'), return a string represenation of the
hex number they result in. Abort with fatal error, printing the line
number, if conversion is unsuccessful.
Characters ('a') and strings ("abc") are not included in this routine
because there are assumed to have been already converted as part of a
diffent step.
"""
# --- SUBSTEP 1: KNOWN SYMBOL ---
# We test to see if the term is a symbol before it is a number. Therefore,
# by default, terms such as 'abc' will be seen as symbols; hex numbers must
# start with '0x' or '$' if they only have hex letters
s = s.strip()
# We store all symbols in lower case, humans be damned. If the following
# step is omitted, upper- and mixed-case symbols will not be converted
# correctly when inside .BYTE directives
lcs = s.lower()
try:
r = symbol_table[lcs]
except KeyError:
pass
else:
return r
# --- SUBSTEP 2: NUMBER ('1', '%000001') ---
f_num, r = convert_number(s)
if f_num:
return r
# --- SUBSTEP 3: MATH TERM ('[ 1 1 + ]') ---
if (s[0] == LEFTMATH):
_, r = convert_number(do_math(s))
return r
# --- SUBSTEP 3: MODIFICATION ('.lsb 0102', '.msb [ 1 1 + ]') ---
w = s.split()
if (w[0] in MODIFIERS):
# The parameter offered to the modification can be a number, symbol,
# math term etc itself. We isolate it and send it and call ourselves to
# convert it again
rest = s.split(' ', 1)[1]
rt = convert_term(line, rest)
r = MODIFIERS[w[0]](line, rt)
return r
# --- SUBSTEP OOPS: If we made it to here, something is wrong ---
fatal(line, f'Cannot convert term "{s}"')
### OUTPUT DEFINITIONS ###
# TODO make format of 6502/65c02 output prettier by eliminating whitespace
def hide_zero_address(n):
"""Given the address of an instruction, if it is zero, return an
empty string, else return a six-character hex string
"""
if n == 0:
return ' '
else:
if MPU == '65816':
width = 6
else:
width = 4
return hexstr(width, n)
def listing_header(l):
"""Create a header for all lines, regardless of type. Takes a line object
and returns a string.
"""
if MPU == '65816':
h = '{0:4}:{1:03} | {2} {3} | {4} {5:2} {6:2} |'.\
format(l.ln, l.sec_ln, l.status, l.type, l.mode, l.a_width,\
l.xy_width)
else:
h = '{0:4}:{1:03} | {2} {3} |'.format(l.ln, l.sec_ln, l.status, l.type)
return h
def listing_comment(l):
"""Given a line object that contains a full-line comment, create a string
for full-line comments. Assumes that the header will be added by calling
program.
"""
return ' | | '+l.raw.rstrip() # rstrip() is paranoid
def listing_whitespace(l):
"""Given a line object that contains whitespace, return a string. Assumes
that the header will be added by calling program.
"""
return ' | |'
def listing_instruction(l):
"""Template for instructions for the Intermediate Representation.
Takes a line object and returns a string for writing to the file.
Assumes that the header will be added by the caller.
"""
s = ' {0:6} | {1:11} | {2:36} {3}'.\
format(hide_zero_address(l.address), l.bytes,\
INDENT+INDENT+l.action+' '+l.parameters, l.il_comment)
return s
def listing_directive(l):
"""Template for directives for the Intermediate Representation.
Takes a line object and returns a string for writing to the file.
"""
# If we get a data directive, we might have to add a table
table = ''
# Some directives would overflow the line, we can simplify
if l.action in ['.advance', '.skip', '.save']:
b_list = '({0}x 00)'.format(l.size)
else:
b_list = l.bytes
# Data directives can overflow a line so we have to treat them separately
if l.action in DATA_DIRECTIVES:
b_list = '({0} bytes)'.format(l.size)
table_header = '\n'+listing_header(l)+\
(' '*8)+'|'+(' '*13)+'|'+INDENT+INDENT
table_line = table_header
ascii_line = ''
c = 0
for b in l.bytes.split():
table_line = table_line+' {0}'.format(b)
char = chr(int(b, 16))
if char not in string.printable:
char = '.'
ascii_line = ascii_line+' '+char
c += 1
if c % 8 == 0:
table = table+'{0:96} -- {1}'.format(table_line, ascii_line)
ascii_line = ''
table_line = table_header
table = table+'{0:96} -- {1}'.format(table_line, ascii_line)
lp = INDENT+l.action+' '+l.parameters
# Some lines are just too long
if len(lp) > 70:
lp = lp[:65]+' (...)'
s = ' {0:6} | {1:11} | {2:36} {3}{4}'.\
format(hide_zero_address(l.address), b_list, lp, l.il_comment, table)
return s
def listing_label(l):
"""Template for a line object that contains a label, returns a string.
Assumes that the header will be added by calling program.
"""
# TODO add colon at end of label
s = ' {0:6} | | {1:36} {2}'.\
format(hide_zero_address(l.address), l.action, l.il_comment)
return s
def listing_control(l):
"""Template for a line object that contains a control instruction.
Returns a string. Assumes that the header will be added by calling
program.
"""
s = ' | | {0:11}'.format(INDENT+l.action)
return s
line_listing_types = {
INSTRUCTION: listing_instruction,
COMMENT: listing_comment,
WHITESPACE: listing_whitespace,
CONTROL: listing_control,
DIRECTIVE: listing_directive,
LABEL: listing_label }
def make_listing(src):
"""Given a list of line objects, return a list of strings with each
line processed for user output.
"""
listing = []
# Header
listing.append(TITLE_STRING)
listing.append(f'Code listing for file {args.source}')
listing.append(f'Generated on {time.asctime(time.localtime())}')
listing.append(f'Target MPU: {MPU}')
if n_external_files != 0:
listing.append(f'External files loaded: {n_external_files}')
listing.append(f'Number of passes executed: {n_passes}')
listing.append(f'Number of steps executed: {n_steps}')
time_end = timeit.default_timer()
listing.append('Assembly time: {0:.5f} seconds'.format(time_end - time_start))
if n_warnings != 0:
listing.append(f'Warnings generated: {n_warnings}')
listing.append('Code origin: {0:06x}'.format(LC0))
listing.append(f'Bytes of machine code: {code_size}')
# Code listing
listing.append('\nLISTING:')
listing.append(' Line Status/Type State/Width Address Bytes Instruction')
for line in src:
try:
l = line_listing_types[line.type](line)
except KeyError:
fatal(line, 'ERROR: Unknown line type "{0}" in line {1}:{2}'.\
format(line.type, line.ln, line.sec_ln))
else:
listing.append(listing_header(line) + l)
# Add macro list
listing.append('\nMACROS:')
if len(macros) > 0:
for m in macros.keys():
listing.append(f'Macro "{m}"')
for ml in macros[m]:
listing.append(f' {ml.action}')
else:
listing.append(INDENT+'(none)')
# Only add symbol table if we have one already
if symbol_table:
listing.append('\nSYMBOL TABLE:')
if len(symbol_table) <= 0:
listing.append(' - (symbol table is empty)\n')
# Find longest symbol name in table
max_sym_len = max([len(k) for k in symbol_table.keys()])
for v in sorted(symbol_table):
listing.append('- {0:{width}} : {1:06x}'.format(v, symbol_table[v], width=max_sym_len))
return listing
#####################################################################
### PASSES AND STEPS ###
# A STEP is executed once, a PASS can be excuted more than once, but usually
# only once per line
# -------------------------------------------------------------------
# STEP BANNER: Set up timing, print banner
# This step is not counted
verbose(TITLE_STRING)
time_start = timeit.default_timer()
verbose('Beginning assembly. Timer started.')
# -------------------------------------------------------------------
# STEP LOAD: Load original source code and add line numbers
# Line numbers start with 1 because this is for humans.
raw_source = []
with open(args.source, 'r') as f:
for ln, ls in enumerate(f.readlines(), 1):
line = CodeLine(ls.rstrip(), ln, 0) # right strip gets rid of LF
raw_source.append(line)
n_steps += 1
verbose(f'STEP LOAD: Read {len(raw_source)} lines from {args.source}')
# -------------------------------------------------------------------
# PASS INCLUDE: Add content from external files specified by the INCLUDE
# directive.
#
# REQUIRED as first step of processing
# The .include directive must be alone in the line and the second string must be
# the name of the file without any spaces or quotation marks. Note that this
# means there will be no .include directives visible in the code listings, since
# everything will be one big file
expanded_source = []
for line in raw_source:
# We haven't converted everything to lower case yet so we have to do it the
# hard way here. It is not legal to have a label in the same line as a
# .include directive. Any inline comment after .include is silently
# discarded
w = line.raw.split()
if len(w) > 1 and w[0].lower() == '.include':
# Keep the line number of the .include directive for later reference
# but add secondary line numbers for reference
with open(w[1], 'r') as f:
for sln, ls in enumerate(f.readlines(), 1):
nl = CodeLine(ls.rstrip(), line.ln, sln)
expanded_source.append(nl)
n_external_files += 1
verbose(f'- Included code from file "{w[1]}"')
else:
expanded_source.append(line)
n_passes += 1
verbose(f'PASS INCLUDE: Added {n_external_files} external file(s)')
# -------------------------------------------------------------------
# PASS EMPTY: Process empty lines
#
# REQUIRES inclusion of all lines from all includes
# REQUIRED for search for MPU type
# We want to cut down the number of lines we have to process as early as
# possible, so we handle empty lines right now
for line in expanded_source:
if not line.raw.strip():
line.type = WHITESPACE
line.status = DONE
n_empty_lines += 1
n_passes += 1
verbose(f'PASS EMPTY: Found {n_empty_lines} empty line(s)')
# -------------------------------------------------------------------
# PASS COMMENTS: Remove comments that span whole lines
#
# REQUIRES inclusion of all lines from all includes
for line in expanded_source:
if line.status == DONE:
continue
# Whole-line comment marked by ';'
if line.raw.strip()[0] == COMMENT_MARKER:
line.type = COMMENT
line.status = DONE
n_comment_lines +=1
n_passes += 1
verbose(f'PASS COMMENTS: Found {n_comment_lines} full-line comment(s)')
# -------------------------------------------------------------------
# PASS MPU: Find MPU type
#
# REQUIRES inclusion of all lines from all includes
# REQUIRES that empty lines have been identified
# ASSUMES that no directives have been processed yet
# REQUIRED for loading mnemonics list
for line in expanded_source:
if line.status == DONE:
continue
# We haven't converted to lower case yet so we have to do this by hand
# It is not legal to have a label in the same line as the .mpu
# directive. Any inline comment after .mpu is silently discarded
s = line.raw.lstrip()
w = s.split()
w1 = w[0] # get first word in line
if w1.lower() != '.mpu':
continue
try:
MPU = w[1] # get second word in line
except IndexError:
fatal(line, 'No MPU given with ".mpu" directive')
else:
line.type = DIRECTIVE
line.status = DONE
line.action = '.mpu'
line.parameters = MPU
break
if MPU not in SUPPORTED_MPUS:
fatal(line, f'MPU "{MPU}" not supported')
if not MPU:
fatal(line, 'No ".mpu" directive found')
n_passes += 1
verbose(f'PASS MPU: Found MPU "{MPU}", this MPU is supported')
# -------------------------------------------------------------------
# STEP OPCODES: Load opcodes depending on MPU type
#
# REQUIRES MPU type is known
# REQUIRED to generate mnemonic list
# We use 65816 as the default. This step does not change the source code.
# Rewrite this for more than three MPU types.
if MPU == '6502':
from opcodes6502 import opcode_table
elif MPU.lower() == '65c02':
from opcodes65c02 import opcode_table
else:
from opcodes65816 import opcode_table
# We used to check the number of opcodes to make sure there weren't more than
# 256, however, with the inclusion of 'lda.8' etc. this is not useful anymore
n_steps += 1
verbose(f'STEP OPCODES: Loaded opcode table for MPU {MPU}')
# -------------------------------------------------------------------
# STEP MNEMONICS: Generate mnemonic list from opcode table
#
# REQUIRES opcodes loaded depending on CPU type
mnemonics = {opcode_table[n][1]:n for n, e in enumerate(opcode_table)}
# For the 6502 and 65c02, we have 'UNUSED' for the entries in the opcode table
# that are, well, not used. We get rid of them here. The 65816 does not have
# any unused opcodes.
if MPU != '65816':
del mnemonics['UNUSED']
n_steps += 1
verbose('STEP MNEMONICS: Generated mnemonics list')
verbose(f'- Number of mnemonics found: {len(mnemonics.keys())}')
# -------------------------------------------------------------------
# PASS SPLIT LABEL: Move labels to their own line
#
# REQUIRES inclusion of all lines from all includes
# REQUIRES list of legal mnemonics available
# ASSUMES all empty lines have been taken care of
# Though Simpler Assembler Notation requires labels to be in a separate line, we
# should be able to assemble code that hasn't been correctly formatted.
relabeled_source = []
# This is pretty short for a function but we might be changing the requirements
# for labels again at some point (such as, must start with a letter).
def is_label(s):
"""Given a string without whitespace, check to see if it ends in a colon,
which defines it as a label.
"""
have_label = False # most words will not be labels
if s[-1] == LABEL_MARKER:
have_label = True
return have_label
for line in expanded_source:
if line.status == DONE:
relabeled_source.append(line)
continue
# While we're at it, we save information about the other lines that we get
# as a side effect
# w has to have at least one word because we've gotten rid of all empty
# lines
w = line.raw.split()
w1 = w[0]
# Directives start with a dot. We just remember that we've found one, but
# don't process it yet
if w1[0] == '.':
line.type = DIRECTIVE
relabeled_source.append(line)
continue
# We know all our mnemonics. We just remember that we've found one, but
# don't process it yet. Silly user might have given us uppercase mnemonics,
# but we accept this gracefully for the moment and stick it to him later
if w1.lower() in mnemonics:
line.type = INSTRUCTION
relabeled_source.append(line)
continue
# We should have a label. For the moment, we just group anonymous labels
# with normal labels.
if (not w1 == LOCAL_LABEL) and (not is_label(w1)):
fatal(line, f'Expecting label, found "{w1}", label missing ":"?')
# We put the label in the action field of the line for later processing
line.type = LABEL
line.status = MODIFIED
line.action = w1.strip()
# If there was only one word in the line, it has to be the label and
# we can go on to the next line as quickly as possible
if len(w) == 1:
relabeled_source.append(line)
continue
# Nope, there is more on the line. We create a new line and come back and
# figure it out what it was. We delete the label from the string. Note this
# can lead to weird effects if the label string appears again in the rest of
# the line - say, an inline comment - but we'll live with that risk for now
rest_of_line = line.raw.replace(w1, '').strip()
# We check again if this is an instruction or a directive. The duplication
# of code is annoying, but makes processing faster because we bug out of
# simple directive lines earlier
rw = rest_of_line.split()
rw1 = rw[0]
# The simple case is that we have a comment after the label, and can just
# put it in the inline comment field without adding another line
if rw1[0] == ';':
line.il_comment = rest_of_line.strip()
relabeled_source.append(line)
continue
# Whatever happens now, the label itself is safe
relabeled_source.append(line)
if rw1[0] == '.':
newline = CodeLine(rest_of_line, line.ln, 1)
newline.type = DIRECTIVE
relabeled_source.append(newline)
continue
if rw1.lower() in mnemonics:
newline = CodeLine(rest_of_line, line.ln, 1)
newline.type = INSTRUCTION
relabeled_source.append(newline)
continue
# If we reach this point, we have something weird on the new line and give
# up with a fatal error
fatal(line, f'Unidentified characters "{rest_of_line}" after label')
n_passes += 1
verbose('PASS SPLIT LABELS: Split lines that have code following their labels')
# -------------------------------------------------------------------
# CLAIM: All labels should now be in a line of their own. Also, all directives
# and instruction lines should be identified
verbose('CLAMING all labels are in a line of their own')
# -------------------------------------------------------------------
# PASS VALIDATE TYPE: Confirm the type of every single line is known
#
# REQUIRES labels to be in own lines
# REQUIRES all types to have been identified
# This step does not change the source
for line in relabeled_source:
if line.type == UNKNOWN:
fatal(line, 'Line of unknown type remaining after processing')
n_passes += 1
verbose('PASS VALIDATE TYPE: All lines are of known type')
# -------------------------------------------------------------------
# PASS INLINE COMMENTS: Isolate inline comments
#
# REQUIRES all types to have been identified
# REQUIRES all types to be in a line of their own
for line in relabeled_source:
if line.status == DONE: