-
Notifications
You must be signed in to change notification settings - Fork 5
/
foco65
executable file
·2007 lines (1841 loc) · 34.5 KB
/
foco65
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 python2
# foco65
# Copyright (C) 2014,2018 Piotr Wiszowaty
#
# 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/}.
import argparse
import re
import sys
#####
class StackUnderflow(Exception):
def __init__(self, text, filename, line, column):
self.filename = filename
self.text = text
self.line = line
self.column = column
def __str__(self):
return "stack underflow (%s,%d,%d): %s" % (self.filename, self.line, self.column, self.text)
class StackNotEmpty(Exception):
def __init__(self, filename, line, column):
self.filename = filename
self.line = line
self.column = column
def __str__(self):
return "stack not empty (%s,%d,%d)" % (self.filename, self.line, self.column)
class ParseError(Exception):
def __init__(self, message, filename, line, column):
self.message = message
self.line = line
self.column = column
self.filename = filename
def __str__(self):
return "%s at line %d column %d in file %s" % (self.message, self.line, self.column, self.filename)
class UnknownWord(ParseError):
def __init__(self, filename, token):
ParseError.__init__(self, "unknown word '%s'" % token.text, filename, token.line, token.column)
class UnexpectedEndOfStream(ParseError):
def __init__(self, filename, line, column):
ParseError.__init__(self, "unexpected end of input", filename, line, column)
class NoSuchFile(ParseError):
def __init__(self, filename, token):
ParseError.__init__(self, "No such include file '%s'" % token.text, filename, token.line, token.column)
#####
class Token:
def __init__(self, text, line, column):
self.text = text
self.line = line
self.column = column
def __eq__(self, other):
return self.text == other
def __str__(self):
return "'%s' %d,%d" % (self.text, self.line, self.column)
def endswith(self, s):
return self.text.endswith(s)
def replace(self, s_from, s_to):
return self.text.replace(s_from, s_to)
def canon(self):
return self.text.replace("-", "_").replace("?", "_is_")
#####
class Input:
WHITESPACE = " \t\n"
EOL = "\n"
def __init__(self, text):
self.text = text
self.offset = 0
self.line = 1
self.column = 1
def __iter__(self):
return self
def mark_start(self):
self._mark_start = self.offset
def mark_end(self):
self._mark_end = self.offset
def marked(self):
return self.text[self._mark_start:self._mark_end]
def end(self):
return self.offset >= len(self.text)
def current_char(self):
if self.end(): return None
return self.text[self.offset]
def next_char(self):
if self.end():
raise UnexpectedEndOfStream(self.current_file_name, self.line, self.column)
c = self.text[self.offset]
self.offset += 1
if c in self.EOL:
self.line += 1
self.column = 1
else:
self.column += 1
return c
def skip_to_eol(self):
while self.current_char() != "\n":
self.next_char()
def next(self):
while self.current_char() in self.WHITESPACE:
self.next_char()
if self.end(): return None
if self.end(): raise StopIteration
line, column, start = self.line, self.column, self.offset
while self.current_char() not in self.WHITESPACE:
self.next_char()
return Token(self.text[start:self.offset], line, column)
#####
class Code:
def __init__(self, code, section):
self.code = code
self.section = section
def output(self, section):
if section == self.section:
return self.code[1:] + "\n"
else:
return ""
#####
class Word:
def __init__(self, name, section, code="", label=None):
self.name = name
self.section = section
self.thread = ["enter"]
self.names = []
self.code = code
if label:
self.label = label
else:
self.label = name
self.recursive = False
self.used = False
def output(self, section):
if self.used and self.section == section:
if self.code:
cout = self.code.output(section)
return "%s\n dta a(*+2)\n%s\n" % (self.label, cout)
else:
s = "\n".join(map(lambda l: " dta a(%s)" % l, self.thread))
return "%s\n%s\n\n" % (self.label, s)
else:
return ""
def __iter__(self):
return iter(self.names)
def add(self, label, name=None):
self.thread.append(label)
if name is not None:
self.names.append(name)
def ip(self):
return len(self.thread)
#####
class RefBase:
def __init__(self, name, label, value, text_section, data_section):
self.name = name
self.value = value
self.text_section = text_section
self.data_section = data_section
self.used = False
def output(self, section):
if self.used:
if section == self.text_section:
return self.text_output
elif section == self.data_section:
return self.data_output
else:
return ""
else:
return ""
def __iter__(self):
return iter([])
class Constant(RefBase):
def __init__(self, name, label, value, text_section, data_section):
RefBase.__init__(self, name, label, value, text_section, data_section)
self.label = "const_" + label
self.text_output = "%s\n dta a(const),a(%s)\n" % (self.label, label)
self.data_output = "%s equ %s\n" % (label, self.value)
class Variable(RefBase):
def __init__(self, name, label, size, text_section, data_section):
RefBase.__init__(self, name, label, None, text_section, data_section)
self.label = "var_" + label
self.text_output = "%s\n dta a(const),a(%s)\n" % (self.label, label)
if size:
self.data_output = "%s equ *\n org *+%d\n" % (label, 2*size)
else:
self.data_output = "%s equ *\n" % label
#####
class BranchTarget:
def __init__(self, ip):
self.ip = ip
self.label = None
def update(self, ip):
if ip > self.ip:
self.label = "*+%d" % (2 * (ip - self.ip))
elif ip < self.ip:
self.label = "*-%d" % (2 * (self.ip - ip))
def __str__(self):
return self.label
#####
class Words:
def __init__(self):
self.lst = []
self.aliases = {"cells": "2*", "cell": "2*", "not": "0="}
def __iter__(self):
return iter(self.lst)
def find(self, name):
if self.aliases.has_key(name):
name = self.aliases[name]
for word in self.lst:
if word.name == name:
return word
return None
def add(self, word):
self.lst.insert(0, word)
#####
class Forth:
def __init__(self, sections):
self.words = Words()
self.items = []
self.sections = sections
self.text_section = "text"
self.data_section = "data"
self.stack = []
self.do_loop_stack = []
self.int_prog = re.compile("-?[0-9]+")
self.hex_prog = re.compile("\$[0-9A-Fa-f]+")
self.state = None
self.inputs = []
def push(self, item):
self.stack.append(item)
def pop(self, token):
if not self.stack:
raise StackUnderflow(token.text, self.current_file_name, token.line, token.column)
else:
return self.stack.pop()
def push_do_loop(self):
self.do_loop_stack.append([])
def push_do_loop_leave(self, branch_target):
self.do_loop_stack[-1].append(branch_target)
def pop_do_loop(self, token):
if not self.do_loop_stack:
raise StackUnderflow(token.text, self.current_file_name, token.line, token.column)
else:
return self.do_loop_stack.pop()
def add_word(self, word):
self.words.add(word)
self.items.append(word)
def isnumber(self, token):
return token is not None and \
(self.int_prog.match(token.text) or \
self.hex_prog.match(token.text))
def tonumber(self, x):
if type(x) == int:
return x
elif self.hex_prog.match(x):
return int(x[1:], 16)
else:
return int(x)
def next(self):
token = self.input.next()
if token == "\\":
self.input.skip_to_eol()
return self.next()
elif token == "(":
while not token.endswith(")"):
token = self.input.next()
return self.next()
else:
return token
def set_state(self, state):
self.state = state
def parse_input(self, input, current_file_name):
self.input = input
self.current_file_name = current_file_name
self.set_state("interpret")
while not self.input.end():
if self.state == "interpret":
self.interpret()
elif self.state == "compile":
self.compile(self.word)
def interpret(self):
token = self.next()
if token == ":":
token = self.next()
self.word = Word(token.text, self.text_section, label=token.canon())
self.set_state("compile")
elif token == "[include]":
token = self.next();
include_file_name = token.text.replace('"', '')
try:
self.inputs.append((self.input, self.current_file_name))
with open(include_file_name, "rt") as f:
self.parse_input(Input(f.read()), include_file_name)
self.input, self.current_file_name = self.inputs.pop()
except IOError:
raise NoSuchFile(self.current_file_name, token)
elif token == "[code]":
self.items.append(self.parse_code())
elif token == "[text-section]":
self.text_section = self.parse_section()
elif token == "[data-section]":
self.data_section = self.parse_section()
elif token == "variable":
self.parse_variable(1)
elif token == "2variable":
self.parse_variable(2)
elif token == "constant":
self.parse_constant(token)
elif token == "create":
self.parse_create()
elif token == ",":
self.parse_comma(token)
elif token == "c,":
self.parse_c_comma(token)
elif token == ',"':
self.parse_comma_doublequote(True)
elif token == '"':
self.parse_comma_doublequote(False)
elif token == ",'":
self.parse_comma_quote(True)
elif token == "'":
self.parse_comma_quote(False)
elif token == "allot":
self.parse_allot(token)
elif token == "+":
x2 = self.pop(token)
x1 = self.pop(token)
self.push(x1 + x2)
elif token == "-":
x2 = self.pop(token)
x1 = self.pop(token)
self.push(x1 - x2)
elif token == "*":
x2 = self.pop(token)
x1 = self.pop(token)
self.push(x1 * x2)
elif token == "cells":
x = self.pop(token)
self.push(2 * x)
elif token == "/":
x2 = self.pop(token)
x1 = self.pop(token)
self.push(x1 / x2)
elif token == "]":
self.set_state("compile")
elif self.isnumber(token):
self.push(self.tonumber(token.text))
elif token is not None:
word = self.words.find(token.text)
if word is not None:
word.used = True
if isinstance(word, Constant):
self.push(self.tonumber(word.value))
else:
self.push(word.name)
else:
raise UnknownWord(self.current_file_name, token)
def compile(self, word):
if self.input.end():
raise UnexpectedEndOfStream(self.current_file_name, self.input.line, self.input.column)
token = self.next()
if token == ";":
word.add("exit")
self.add_word(word)
self.set_state("interpret")
elif token == "recursive":
word.recursive = True
elif token == "[label]":
token = self.next()
word.label = token.text
elif token == "[code]":
word.code = self.parse_code()
elif token == "begin":
self.push(word.ip())
elif token == "again":
word.add("branch")
begin_ip = self.pop(token)
target = BranchTarget(word.ip())
target.update(begin_ip)
word.add(target)
elif token == "until":
word.add("until")
begin_ip = self.pop(token)
target = BranchTarget(word.ip())
target.update(begin_ip)
word.add(target)
elif token == "if":
word.add("_if")
target = BranchTarget(word.ip())
word.add(target)
self.push(target)
elif token == "else":
word.add("branch")
target1 = BranchTarget(word.ip())
word.add(target1)
target0 = self.pop(token)
target0.update(word.ip())
self.push(target1)
elif token == "then":
target = self.pop(token)
target.update(word.ip())
elif token == "while":
word.add("while", "while")
target = BranchTarget(word.ip())
word.add(target)
self.push(target)
elif token == "repeat":
word.add("branch")
target1 = self.pop(token)
begin_ip = self.pop(token)
target0 = BranchTarget(word.ip())
target0.update(begin_ip)
word.add(target0)
target1.update(word.ip())
elif token == "[":
self.set_state("interpret")
elif token == "literal":
self.word.add("lit")
tos = self.pop(token)
if isinstance(tos, int):
txt = str(tos)
elif isinstance(tos, str):
txt = tos
else:
txt = tos.output(self.text_section)
self.word.add(txt)
elif token == "do":
word.add("do", "do")
self.push(word.ip())
self.push_do_loop()
elif token == "loop" or token == "+loop":
word.add(token.text.replace("+", "plus_"), token.text)
do_ip = self.pop(token)
target = BranchTarget(word.ip())
target.update(do_ip)
word.add(target)
for leave in self.pop_do_loop(token):
leave.update(word.ip())
elif token == "leave":
word.add("unloop", "unloop")
word.add("branch")
target = BranchTarget(word.ip())
word.add(target)
self.push_do_loop_leave(target)
elif token == "lit":
word.add("lit")
token = self.next()
word.add(token.text, token.text)
else:
if word.recursive and token == word.name:
subword = word
else:
subword = self.words.find(token.text)
if subword is not None:
word.add(subword.label, subword.name)
else:
if self.isnumber(token):
word.add("lit")
word.add(token.text)
else:
raise UnknownWord(self.current_file_name, token)
def parse_code(self):
self.input.mark_start()
while True:
self.input.mark_end()
token = self.next()
if token == "[end-code]":
return Code(self.input.marked(), self.text_section)
def parse_section(self):
token = self.next()
return token.text
def parse_variable(self, size):
token = self.next()
name = token.text
label = token.canon()
word = Variable(name, label, size, self.text_section, self.data_section)
self.add_word(word)
def parse_constant(self, token):
token = self.next()
num = self.pop(token)
word = Constant(token.text, token.canon(), num, self.text_section, self.data_section)
self.add_word(word)
def parse_create(self):
token = self.next()
name = token.text
label = token.canon()
word = Variable(name, label, 0, self.text_section, self.data_section)
self.add_word(word)
def parse_allot(self, token):
count = self.pop(token)
self.items.append(Code("\n org *+%d" % count, self.data_section))
def parse_comma(self, token):
item = Code("\n dta a(%s)" % self.pop(token), self.data_section)
self.items.append(item)
def parse_c_comma(self, token):
item = Code("\n dta %d" % self.pop(token), self.data_section)
self.items.append(item)
def parse_comma_doublequote(self, counted):
# allocate ASCII string
self.input.mark_start()
while True:
token = self.next()
if token.endswith('"'):
self.input.mark_end()
text = self.input.marked()[1:-1]
if counted:
count = "%d," % len(text)
else:
count = ""
item = Code("\n dta %sc'%s'" % (count, text), self.data_section)
self.items.append(item)
break
def parse_comma_quote(self, counted):
# allocate ANTIC string
self.input.mark_start()
while True:
token = self.next()
if token.endswith("'") or token.endswith("'*"):
self.input.mark_end()
if token.endswith("*"):
text = self.input.marked()[1:-2]
inverse = "*"
else:
text = self.input.marked()[1:-1]
inverse = ""
if counted:
count = "%d," % len(text)
else:
count = ""
item = Code("\n dta %sd'%s'%s" % (count, text, inverse), self.data_section)
self.items.append(item)
break
def filter_used_words(self, name):
word = self.words.find(name)
if word is not None:
if not word.used:
word.used = True
for name in word:
self.filter_used_words(name)
def generate_output(self):
self.filter_used_words("main")
if self.stack:
raise StackNotEmpty(self.current_file_name, self.input.line, self.input.column)
section_outputs = []
for section in self.sections:
section_outputs.append("; section %s\n" % section)
item_outputs = map(lambda i: i.output(section), self.items)
section_outputs.append("".join(item_outputs))
return "\n".join(section_outputs)
#####
boot_text = """
[text-section] boot
[code]
ip equ $18
w equ $1A
z equ $1C
cntr equ $1E
tmp equ $15
tmp2 equ $3D
pstack equ %(pstack_bottom)s
boot
ldx #%(pstack_size)d
lda #<[main+2]
sta ip
lda #>[main+2]
sta ip+1
jmp next
; push ip
; ip := w+2
; jmp next
enter
lda ip
pha
lda ip+1
pha
lda #2
clc
adc w
sta ip
lda #0
adc w+1
sta ip+1
jmp next
; pop ip
; jmp next
exit
dta a(*+2)
pla
sta ip+1
pla
sta ip
;jmp next
; w := (ip)
; ip := ip+2
; z := (w)
; jmp (z)
next
ldy #0
lda (ip),y
sta w
iny
lda (ip),y
sta w+1
lda #2
clc
adc ip
sta ip
lda #0
adc ip+1
sta ip+1
ldy #0
lda (w),y
sta z
iny
lda (w),y
sta z+1
jmp (z)
; push (ip)
; ip := ip+2
lit
dta a(*+2)
ldy #1
lda (ip),y
dey
dex
sta pstack,x
lda (ip),y
dex
sta pstack,x
lda #2
clc
adc ip
sta ip
lda #0
adc ip+1
sta ip+1
jmp next
const
ldy #3
lda (w),y
dey
dex
sta pstack,x
lda (w),y
dex
sta pstack,x
jmp next
_if
dta a(*+2)
lda pstack,x
inx
ora pstack,x
bne _if_t
_if_f
ldy #0
lda (ip),y
sta w
iny
lda (ip),y
sta ip+1
lda w
sta ip
inx
jmp next
_if_t
lda #2
clc
adc ip
sta ip
lda #0
adc ip+1
sta ip+1
inx
jmp next
branch
dta a(*+2)
ldy #0
lda (ip),y
sta w
iny
lda (ip),y
sta ip+1
lda w
sta ip
jmp next
until
dta a(*+2)
lda pstack,x
inx
ora pstack,x
bne until_end
until_repeat
inx
; ip := (ip)
ldy #0
lda (ip),y
iny
sta w
lda (ip),y
sta ip+1
lda w
sta ip
jmp next
until_end
inx
; ip := ip+2
clc
lda #2
adc ip
sta ip
lda #0
adc ip+1
sta ip+1
jmp next
[end-code]
"""
basewords_text = """
[text-section] text
: drop
[code]
inx
inx
jmp next
[end-code] ;
: nip
[code]
lda pstack,x
sta pstack+2,x
inx
lda pstack,x
sta pstack+2,x
inx
jmp next
[end-code] ;
: while
[code]
lda pstack,x
inx
ora pstack,x
beq while_end
inx
lda #2
clc
adc ip
sta ip
lda #0
adc ip+1
sta ip+1
jmp next
while_end
inx
ldy #0
lda (ip),y
iny
sta w
lda (ip),y
sta ip+1
lda w
sta ip
jmp next
[end-code] ;
: @
[label] fetch
[code]
lda pstack,x
inx
sta w
lda pstack,x
sta w+1
ldy #1
lda (w),y
sta pstack,x
dey
lda (w),y
dex
sta pstack,x
jmp next
[end-code] ;
: c@
[label] c_fetch
[code]
lda pstack,x
inx
sta w
lda pstack,x
sta w+1
lda #0
sta pstack,x
ldy #0
lda (w),y
dex
sta pstack,x
jmp next
[end-code] ;
: ! ( x addr -- )
[label] store
[code]
lda pstack,x
inx
sta w
lda pstack,x
inx
sta w+1
lda pstack,x
inx
ldy #0
sta (w),y
iny
lda pstack,x
inx
sta (w),y
jmp next
[end-code] ;
: c!
[label] c_store
[code]
lda pstack,x
inx
sta w
lda pstack,x
inx
sta w+1
lda pstack,x
inx
inx
ldy #0
sta (w),y
jmp next
[end-code] ;
: + ( n1|u1 n2|u2 -- n3|u3 )
[label] plus
[code]
lda pstack,x
inx
ldy pstack,x
inx
clc
adc pstack,x
sta pstack,x
tya
adc pstack+1,x
sta pstack+1,x
jmp next
[end-code] ;
\ n1|u1 - n2|u2
: - ( n1|u1 n2|u2 -- n3|u3 )
[label] minus
[code]
sec
lda pstack+2,x
sbc pstack+0,x
sta pstack+2,x
inx
lda pstack+2,x
sbc pstack+0,x
sta pstack+2,x
inx
jmp next
[end-code] ;
: 1+
[label] one_plus
[code]
clc
lda #1
adc pstack,x
sta pstack,x
lda #0
adc pstack+1,x
sta pstack+1,x
jmp next
[end-code] ;
: 1-
[label] one_minus
[code]
sec
lda pstack,x
sbc #1
sta pstack,x
lda pstack+1,x
sbc #0
sta pstack+1,x