-
Notifications
You must be signed in to change notification settings - Fork 5
/
rforth.py
executable file
·2967 lines (2449 loc) · 93.2 KB
/
rforth.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 python
#
# (c) 2005-2017 Samuel Tardieu <[email protected]>
#
# rforth1 is released under the GNU General Public License (see the
# file COPYING in this directory)
"""Forth compiler targetting the PIC18Fxxx microcontrollers family.
Memory usage:
- BSR always points onto bank 1 where variables will be preferably stored
- for a 16 bits value, low byte is stored at the lowest address
- data stack is indexed by FSR0; stack grows upward; low byte is pushed
first and high byte next; INDF0 points onto the latest high byte pushed
- data stack is located starting at 0x60 to let short-addressable part
of memory bank 0 free for user use
- FSR1 is used for indirect memory access
- FSR2 is used for a return stack located starting at 0xc0 in bank 0;
data are stored MSB first on this stack to ease transfers between
stacks
- RAM cells are using address between 0x0000 and 0x0FFF. EEPROM will
be designated as an address between 0x1000 and 0x1FFF. Flash will
use bounds of 0x8000 and 0xFFFF.
- core defined variables are located between 0x000 and 0x05f (in the first
bank) and are not zero-initialized; they are typically temporary
variables used in computations
- user-defined variables are located starting at 0x0100"""
import optparse
import os
import re
import string
import sys
compiler = None
warnings_as_errors = False
DEFAULT_PROCESSOR = '18f248'
# Setup Forth search path. The search path is the current directory
# then the directories in RFORTH1_PATH (if any) then rforth1 directory
forth_search_path = ['.']
try:
forth_search_path += os.getenv('RFORTH1_PATH').split(os.path.pathsep)
except AttributeError:
pass
forth_search_path.append(os.path.dirname(sys.argv[0]))
def forth_open(path, mode):
"""Open a file according to the Forth search path if the name is relative."""
if path[0] not in [os.path.sep, os.path.altsep]:
for p in forth_search_path:
try:
return open(os.path.join(p, path), mode)
except IOError:
pass
# Open locally or get an exception
return open(path, mode)
def parse_number(str):
"""Parse a string and return a Number object with the right number and the
preferred base for representation."""
sign = 1
while str[:1] == '-':
sign, str = -sign, str[1:]
for prefix, base in [('$', 16), ('0x', 16), ('0b', 2), ('', 10)]:
if str.startswith(prefix):
try:
return Number(sign * int(str[len(prefix):], base), base)
except:
return None
return None
def stderror(str):
"""Write a string on standard error and add a carriage return."""
sys.stderr.write("%s\n" % str)
def warning(str):
"""Print a warning on standard error."""
if warnings_as_errors:
error(str)
else:
stderror('WARNING: ' + str)
def error(str):
"""Print a fatal error on standard error."""
stderror('ERROR: ' + str)
def make_tuple(insn, parameters):
return insn, tuple(parameters)
def octet(n):
"""Check whether n is between 0 and 255."""
return n >= 0 and n <= 255
class LiteralValue:
"""Represent any literal value that can be put on the stack."""
def static_value16(self):
v = self.static_value()
if v is None:
return None
return v & 0xffff
def makes_reference_to(self, l):
return False
class Number(LiteralValue):
def __init__(self, value, base=10):
self.value = value
self.base = base
def __repr__(self):
if self.value < 0:
s = '-'
else:
s = ''
if self.base == 10:
return s + str(abs(self.value))
return s + hex(abs(self.value))
def deep_references(self, stack):
return stack
def static_value(self):
return self.value
def __add__(self, i):
return Number(self.value + i, self.base)
dst_w = "w"
dst_f = "f"
access = "0"
no_access = "1"
no_fast = Number(0)
fast = Number(1)
def in_access_bank(addr):
"""Check whether an address can be accessed through the access bank."""
addr = addr.static_value()
return addr is not None and addr <= 0x5f or(addr >= 0xf60 and addr <= 0xfff)
def is_special_register(addr):
"""Check whether an address denotes an internal PIC register."""
a = addr.static_value()
return a >= 0xf00 and a <= 0xfff
def in_bank_1(addr):
"""Check whether an address can be accessed in bank 1 using BSR."""
addr = addr.static_value()
return addr is not None and(addr & 0xff00 == 0x0100)
def short_addr(addr):
"""Check whether an address can be accessed using a short reference, with
or without an access bank."""
return in_access_bank(addr) or in_bank_1(addr)
def access_bit(addr):
"""Return the right access bit depending on whether the address is present
in the access bank or not."""
return access if in_access_bank(addr) else no_access
def ram_addr(addr):
"""Check whether the access designates a RAM address."""
addr = addr.static_value()
return addr is not None and(addr & 0xf000 == 0x0000)
def eeprom_addr(addr):
"""Check whether the access designates an EEPROM address."""
addr = addr.static_value()
return addr is not None and(addr & 0xf000 == 0x1000)
def is_static_push(opcode):
return opcode[0] == 'OP_PUSH' and opcode[1][0].static_value() is not None
def is_ram_fetch(opcode):
return opcode[0] == 'OP_FETCH' and ram_addr(opcode[1][0])
class Named:
immediate = True
section = 'undefined'
inlined = False
inw = False
outw = False
outz = False
from_source = True
referenced_by = 0
not_inlinable = False
definition = None
def __init__(self, name, compile=True):
self.name = name
if compile:
compiler.start_compilation(self)
else:
compiler.enter_object(self)
self.references = []
self.definition = compiler.current_location()
def reset_referenced_by(self):
self.referenced_by = 0
def should_inline(self):
"""Return True if this word should be inlined."""
return False
def can_inline(self):
"""Return True if this word can be inlined."""
return False
def makes_reference_to(self, l):
return False
def deep_references(self, stack):
self.referenced_by += 1
if self in stack:
return
stack.append(self)
for i in self.references:
i.deep_references(stack)
self.prepare()
return stack
def __repr__(self):
name = self.name
if name not in Compiler.all_opcodes:
for k, v in [('?', 'QM'), ('!', 'EX'), ('@', 'AT'), ('+', 'PL'),
('-', '_'), ('*', 'ST'), ('/', 'SL'), ('=', 'EQ'),
('<', 'LT'), ('>', 'GT'), ('$', '_'), ('.', '_'),
('"', 'QU'), ("'", '_'), (':', 'CL'), (';', 'SC'),
('(', 'OP'), (')', 'CP'), ('%', 'PC')]:
if len(v) > 1:
v = '_%s_' % v
name = name.replace(k, v)
if self.occurrence:
suffix = '__%d' % self.occurrence
else:
suffix = ''
if name[0] in string.digits:
prefix = '_'
else:
prefix = ''
name = prefix + name + suffix
if name in Compiler.gpasm_directives:
name = '_' + name
return name
def unsubstituted(self):
return repr(self)
def refers_to(self, object):
if object is None or isinstance(object, (Number, str)):
return
if self != object:
self.references.append(object)
def output_header(self, outfd):
outfd.write('; %s: defined at %s\n' % (self.name, self.definition))
def prepare(self):
pass
def check_real(self):
"""Check whether the current object is real or signal an error if
it is an unresolved forward reference (overriden in Forward)."""
pass
class Binary(LiteralValue):
op = ''
def __init__(self, v1, v2):
self.v1 = v1
self.v2 = v2
def __repr__(self):
return '(%s%s%s)' % (self.v1, self.op, self.v2)
def deep_references(self, stack):
self.v1.deep_references(stack)
self.v2.deep_references(stack)
return stack
def static_value(self):
a1, a2 = self.v1.static_value(), self.v2.static_value()
return self.compute(a1, a2) if a1 is not None and a2 is not None else None
def makes_reference_to(self, l):
return self.v1.makes_reference_to(l) or self.v2.makes_reference_to(l)
class Add(Binary):
op = '+'
def compute(self, a1, a2):
return a1 + a2
class Sub(Binary):
op = '-'
def compute(self, a1, a2):
return a1 - a2
class Mult(Binary):
op = '*'
def compute(self, a1, a2):
return a1 * a2
class Div(Binary):
op = '/'
def compute(self, a1, a2):
return a1 / a2
class LeftShift(Binary):
op = '<<'
def compute(self, a1, a2):
return a1 << a2
class Unary(LiteralValue):
r = ''
def __init__(self, value):
self.value = value
def __repr__(self):
return self.r % self.value
def static_value(self):
a = self.value.static_value()
if a is not None:
return self.compute(a)
def deep_references(self, stack):
return self.value.deep_references(stack)
def makes_reference_to(self, l):
return self.value.makes_reference_to(l)
class Low(Unary):
r = 'LOW(%s)'
def compute(self, a):
return a & 0xff
class High(Unary):
r = 'HIGH(%s)'
def compute(self, a):
return a >> 8
def low(x):
v = x.static_value()
return x if v is not None and v >= 0 and v <= 0xff else Low(x)
def high(x):
v = x.static_value()
return Number(0) if v is not None and v >= 0 and v <= 0xff else High(x)
class Negated(Unary):
r = '(-%s)'
def compute(self, a):
return -a
class Primitive(Named):
pass
class NamedReference(Named):
"""Label with an implicit or explicit name."""
def __init__(self, name=None):
if name is None:
label_name = '_lbl_'
else:
label_name = name
Named.__init__(self, label_name, compile=False)
self.from_source = name is not None
def run(self):
compiler.ct_push(self)
def static_value(self):
return None
class Label(NamedReference):
def makes_reference_to(self, l):
return self == l
class FlashData(NamedReference):
section = 'static data'
from_source = False
def __init__(self, data, original_data, basename=None):
if basename is None:
basename = '_data_'
NamedReference.__init__(self, basename)
self.data = data
self.original_data = original_data
def output_header(self, outfd):
outfd.write('; defined at %s as:\n; %s\n' %
(self.definition, self.original_data))
def output(self, outfd):
outfd.write('%s' % self)
count = -1
for i in self.data:
count += 1
if count % 8 == 0:
count = 0
outfd.write('\n\tdb ')
if count != 0:
outfd.write(',')
outfd.write('%d' % i)
outfd.write('\n')
class Forward(Label):
"""Forward declaration."""
def __init__(self, name):
Label.__init__(self, name)
compiler.start_compilation(self)
def run(self):
if compiler.state:
compiler.add_call(self)
else:
compiler.ct_push(self)
def check_real(self):
compiler.error('%s (defined at %s) needs to be overloaded' %
(self.name, self.definition))
def can_inline(self):
return False
def make_primitive(runfunc):
class _primitive(Primitive):
def run(self, *args):
runfunc(*args)
return _primitive
def register_primitives():
return [(data.__doc__ or name[10:], make_primitive(data))
for (name, data) in globals().items()
if name.startswith('primitive_')]
def primitive_label():
label = Label(compiler.parse_word())
compiler.add_instruction('LABEL', [label])
def primitive_forward():
Forward(compiler.parse_word())
def primitive_intr_protect():
"intr-protect"
compiler.add_instruction('OP_INTR_PROTECT', [])
def primitive_intr_unprotect():
"intr-unprotect"
compiler.add_instruction('OP_INTR_UNPROTECT', [])
def primitive_literal_char():
"[char]"
char = Number(ord(compiler.parse_word()[0]))
if compiler.state:
compiler.push(char)
else:
compiler.ct_push(char)
def primitive_begin():
compiler.ct_push(0)
label = Label()
compiler.ct_push(label)
compiler.add_instruction('LABEL', [label])
def primitive_again(do_not_pop_counter=False):
label = compiler.ct_pop()
compiler.add_instruction('bra', [label])
if not do_not_pop_counter:
assert compiler.ct_pop() == 0
def primitive_ob():
"["
compiler.state = 0
def primitive_cb():
"]"
compiler.state = 1
def primitive_literal():
compiler.push(compiler.ct_pop())
def primitive_to_w(warn=True):
">w"
name, params = compiler.last_instruction()
if name == 'OP_PUSH':
compiler.rewind()
value = params[0]
s = value.static_value()
if warn and s is not None and(s < -128 or s > 255):
compiler.error('value will not fit in W register')
compiler.add_instruction('movlw', [low(value)])
elif name in ['OP_FETCH', 'OP_CFETCH'] and ram_addr(params[0]):
compiler.rewind()
addr = params[0]
if warn and name == 'OP_FETCH':
compiler.warning('value may not fit in W register')
if short_addr(addr):
compiler.add_instruction('movf',
[addr, dst_w, access_bit(addr)])
else:
compiler.add_instruction('movff', [addr, compiler['WREG']])
elif name == 'OP_DUP':
compiler.rewind()
compiler.add_instruction('movlw', [Number(-1)])
compiler.add_instruction('movf', [compiler['PLUSW0'], dst_w, access])
elif name == 'OP_PUSH_W':
compiler.rewind()
else:
compiler.add_instruction('OP_POP_W', [])
def primitive_dup():
name, params = compiler.last_instruction()
if name in ['OP_PUSH', 'OP_PUSH_W']:
compiler.add_instruction(name, params)
elif name in ['OP_CFETCH']:
compiler.rewind()
addr = params[0]
compiler.add_instruction('movf', [addr, dst_w, access_bit(addr)])
compiler.add_instruction('OP_PUSH_W')
compiler.add_instruction('OP_PUSH_W')
else:
compiler.add_instruction('OP_DUP')
def primitive_drop():
name, params = compiler.last_instruction()
if name in ['OP_PUSH', 'OP_DUP']:
compiler.rewind()
elif name in ['OP_FETCH', 'OP_CFETCH'] and ram_addr(params[0]) and \
params[0].static_value() < 0xf60:
# Regular memory read, can be safely removed
compiler.rewind()
else:
compiler['>w'].run(False)
def primitive_from_w():
"w>"
name, params = compiler.last_instruction()
if name == 'OP_POP_W':
compiler.rewind()
# >w w> only keeps the low 8 bits of the TOS
compiler.add_instruction('clrf', [compiler['INDF0'], access])
elif name == 'movf' and params[1] == dst_w:
compiler.rewind()
compiler.push(params[0])
compiler.eval('c@')
else:
compiler.add_instruction('OP_PUSH_W', [])
def primitive_and():
name, params = compiler.last_instruction()
if name == 'OP_PUSH' and octet(params[0].static_value()):
compiler.rewind()
compiler.eval('>w')
compiler.add_instruction('andlw', params)
compiler.eval('w>')
else:
compiler.eval('op_and')
def primitive_to_r():
">r"
name, params = compiler.last_instruction()
if name == 'OP_PUSH':
compiler.rewind()
compiler.add_instruction(
'movff', [high(params[0]), compiler['PREINC2']])
compiler.add_instruction(
'movff', [low(params[0]), compiler['PREINC2']])
else:
compiler.add_instruction(
'movff', [compiler['POSTDEC0'], compiler['PREINC2']])
compiler.add_instruction(
'movff', [compiler['POSTDEC0'], compiler['PREINC2']])
def primitive_keep():
name, params = compiler.last_instruction()
if name == 'OP_PUSH':
compiler.rewind()
compiler.eval('dup >r')
compiler.add_call(params[0])
compiler.eval('r>')
compiler.add_call(params[0])
else:
compiler.eval('(keep)')
def primitive_bi():
name, params = compiler.last_instruction()
if name == 'OP_PUSH':
compiler.rewind()
compiler.eval('keep')
compiler.add_call(params[0])
else:
compiler.eval('(bi)')
def primitive_cfor():
name, params = compiler.last_instruction()
label_uncfor = Label()
label_noloop = Label()
compiler.ct_push(label_noloop)
compiler.ct_push(label_uncfor)
if name in ['OP_FETCH', 'OP_CFETCH'] and ram_addr(params[0]):
compiler.rewind()
addr = params[0]
compiler.add_instruction('movf', [addr, dst_w, access_bit(addr)])
if name == 'OP_FETCH':
compiler.warning('loop index may be larger than one byte')
compiler.add_instruction('movwf', [compiler['PREINC2'], access])
compiler.add_instruction('bz', [label_uncfor])
else:
bound_checks = True
if name == 'OP_PUSH':
value = params[0].static_value()
if value == 0:
compiler.rewind()
compiler.warning('empty loop will not execute')
compiler.add_instruction('bra', [label_noloop])
elif value < 0 or value > 255:
compiler.error('loop limit does not fit in a byte')
elif value is not None:
bound_checks = False
compiler.eval('>w')
compiler.add_instruction('movwf',
[compiler['PREINC2'], access])
if bound_checks:
name, params = compiler.before_last_instruction()
if name != 'OP_POP_W':
compiler.add_instruction('iorlw', [Number(0)])
compiler.add_instruction('bz', [label_uncfor])
compiler.eval('begin')
def primitive_ob_ob():
"[["
label = Label()
compiler.ct_push(label)
compiler.eval('ahead')
compiler.add_instruction('LABEL', [label])
def primitive_cb_cb():
"]]"
compiler.eval('exit then')
compiler.push(compiler.ct_pop())
def primitive_ahead():
label = Label()
compiler.ct_push(label)
compiler.add_instruction('bra', [label])
def primitive_then():
label = compiler.ct_pop()
compiler.add_instruction('LABEL', [label])
def primitive_repeat():
compiler['again'].run(True)
counter = compiler.ct_pop()
for _ in range(counter):
compiler.eval('then')
def primitive_if(invert=False):
name, params = compiler.last_instruction()
if name == 'OP_PUSH':
value = params[0].static_value()
if value == 0:
compiler.rewind()
compiler.warning('constant 0 will never execute')
compiler.eval('ahead')
else:
compiler.rewind()
compiler.warning('constant non-zero will always execute')
label = Label()
compiler.ct_push(label)
return
if name == 'OP_NORMALIZE':
compiler.rewind()
return compiler['if'].run(invert)
if name == 'OP_0=':
compiler.rewind()
return compiler['if'].run(not invert)
if name == 'OP_BIT_SET?':
compiler.rewind()
value = params[0]
bit = params[1]
acc = params[2]
invert = not invert
elif name == 'OP_BIT_CLR?':
compiler.rewind()
value = params[0]
bit = params[1]
acc = params[2]
else:
if name != 'MARKER_ZSET':
compiler.add_instruction('movf', [compiler['POSTDEC0'],
dst_w, access])
compiler.add_instruction('iorwf', [compiler['POSTDEC0'],
dst_w, access])
value, bit = compiler['Z']
acc = access
if invert:
ins = 'btfss'
else:
ins = 'btfsc'
compiler.add_instruction(ins, [value, bit, acc])
compiler.eval('ahead')
def primitive_question_if():
"?if"
compiler.add_instruction('movf', [compiler['POSTDEC0'], dst_w, access])
compiler.add_instruction('iorwf', [compiler['POSTINC0'], dst_w, access])
value, bit = compiler['Z']
compiler.add_instruction('btfsc', [value, bit, access])
compiler.eval('ahead')
# Structure of the switch statement on the compile stack is:
# - next label or None for the first case
# - switch end label
# - xored value
def primitive_switchw():
compiler.ct_push(None)
compiler.ct_push(Label())
compiler.ct_push(0)
def primitive_casew(is_default=False):
if not is_default:
name, params = compiler.last_instruction()
if name != 'OP_PUSH':
raise Compiler.FATAL_ERROR("%s: casew must be used with a constant" %
compiler.current_location)
compiler.rewind()
xored = compiler.ct_pop()
label = compiler.ct_pop()
nlabel = compiler.ct_pop()
if nlabel is not None:
compiler.add_instruction('bra', [label])
compiler.add_instruction('LABEL', [nlabel])
nlabel = Label()
compiler.ct_push(nlabel)
compiler.ct_push(label)
if not is_default:
xored ^= params[0].static_value()
compiler.add_instruction('xorlw', [Number(xored)])
value, bit = compiler['Z']
compiler.add_instruction('btfss', [value, bit, access])
compiler.add_instruction('bra', [nlabel])
compiler.ct_push(params[0].static_value())
else:
compiler.ct_push(xored)
def primitive_endcasew():
pass
def primitive_defaultw():
compiler['casew'].run(True)
def primitive_endswitchw():
_xored = compiler.ct_pop()
label = compiler.ct_pop()
nlabel = compiler.ct_pop()
compiler.add_instruction('LABEL', [nlabel])
compiler.add_instruction('LABEL', [label])
def primitive_literal_address():
"[']"
compiler.push(compiler.find(compiler.parse_word()))
def primitive_execute():
name, params = compiler.last_instruction()
if name == 'OP_PUSH':
compiler.rewind()
compiler.add_call(params[0])
else:
compiler.eval('(execute)')
def primitive_jump():
compiler.add_instruction('clrf', [compiler['PCLATU'], access])
compiler.push(compiler['PCL'])
compiler.eval('!')
def primitive_while(is_until=False):
flabel = compiler.ct_pop()
counter = compiler.ct_pop()
compiler['if'].run(is_until)
compiler.ct_push(counter + 1)
compiler.ct_push(flabel)
def primitive_until():
compiler['while'].run(True)
compiler.eval('repeat')
def primitive_cnext():
compiler.add_instruction('decfsz',
[compiler['INDF2'], dst_f, access])
compiler.eval('again')
label = compiler.ct_pop()
compiler.add_instruction('LABEL', [label])
compiler.add_instruction('movf',
[compiler['POSTDEC2'], dst_f, access])
label = compiler.ct_pop()
compiler.add_instruction('LABEL', [label])
def primitive_else():
compiler.eval('ahead')
compiler.ct_swap()
compiler.eval('then')
def primitive_0_not_equal():
"0<>"
name, _params = compiler.last_instruction()
if name != 'OP_NORMALIZE':
compiler.add_instruction('OP_NORMALIZE', [])
def primitive_0_equal():
"0="
name, _params = compiler.last_instruction()
if name == 'OP_0=':
compiler.rewind()
compiler.eval('0<>')
return
if name == 'OP_NORMALIZE':
compiler.rewind()
compiler.add_instruction('OP_0=', [])
def bitop(kind): # kind can be 'set', 'clear' or 'toggle'
name, params = compiler.last_instruction()
if name == 'OP_PUSH':
# The bit to change is statically known
compiler.rewind()
bit = params[0]
name, params = compiler.last_instruction()
if kind == 'set':
op = 'bsf'
elif kind == 'clear':
op = 'bcf'
elif kind == 'toggle':
op = 'btg'
if name == 'OP_PUSH' and short_addr(params[0]):
# The address can also be access directly
compiler.rewind()
addr = params[0]
compiler.add_instruction(op, [addr, bit, access_bit(params[0])])
else:
# Latch through FSR1
compiler.pop_to_fsr(1)
compiler.add_instruction(op, [compiler['INDF1'], bit,
access])
else:
# Resort to a library function
if kind == 'set':
compiler.eval('op_bit_set')
elif kind == 'clear':
compiler.eval('op_bit_clr')
else:
compiler.eval('op_bit_toggle')
def primitive_bit_set():
"bit-set"
bitop('set')
def primitive_bit_clr():
"bit-clr"
bitop('clear')
def primitive_bit_toggle():
"bit-toggle"
bitop('toggle')
def primitive_bit_is_set(invert=False):
"bit-set?"
name, params = compiler.last_instruction()
if name == 'OP_PUSH':
# The bit to test is statically known
compiler.rewind()
bit = params[0]
name, params = compiler.last_instruction()
if invert:
op = 'OP_BIT_CLR?'
else:
op = 'OP_BIT_SET?'
if name == 'OP_PUSH' and short_addr(params[0]):
# The address is also usable as-is
compiler.rewind()
addr = params[0]
compiler.add_instruction(op, [addr, bit, access_bit(addr)])
else:
# Use FSR1 to latch the address
compiler.pop_to_fsr(1)
compiler.add_instruction(op, [compiler['INDF1'], bit,
access])
else:
# Resort to a library function
if invert: