-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathsecd.py
1989 lines (1560 loc) · 68.6 KB
/
secd.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
"""
Toy implementation of the SECD abstract machine. Follows the
presentation by Peter M. Kogge, The Architecture of Symbolic Computers,
1991, McGraw Hill.
Author: Carlo Hamalainen <[email protected]>
"""
try:
import pydot
from pydotutils import pydot_record_string
except:
pass
import sys
# We have a fixed amount of memory available.
MAX_ADDRESS = 1000
# Memory cells hold either an integer or a nonterminal. For simplicity we
# store an integer as the tuple (TAG_INTEGER, x) where type(x) == int, and
# a nonterminal is of the form (TAG_NONTERMINAL, car, cdr) where car and cdr
# are memory locations.
TAG_INTEGER = 'INT'
TAG_NONTERMINAL = 'NT'
# Opcodes are stored in memory as strings. This is cheating (really we should have
# a bijection ADD <-> 100, MUL <-> 101, etc) but it simplifies debugging.
# Names to make writing code a bit more pleasant (avoids
# heaps of string quoting).
ADD = 'ADD'
AP = 'AP'
CAR = 'CAR'
CDR = 'CDR'
CONS = 'CONS'
DIV = 'DIV'
DUM = 'DUM'
JOIN = 'JOIN'
LD = 'LD'
LDC = 'LDC'
LDF = 'LDF'
MUL = 'MUL'
NIL = 'NIL'
NULL = 'NULL'
RAP = 'RAP'
READC = 'READC'
READI = 'READI'
RTN = 'RTN'
SEL = 'SEL'
STOP = 'STOP'
SUB = 'SUB'
WRITEC = 'WRITEC'
WRITEI = 'WRITEI'
ZEROP = 'ZEROP'
GT0P = 'GT0P'
LT0P = 'LT0P'
OP_CODES = [ADD, # integer addition
MUL, # integer multiplication
SUB, # integer subtraction
DIV, # integer division
NIL, # push nil pointer onto the stack
CONS, # cons the top of the stack onto the next list
LDC, # push a constant argument (any S-expression) onto the stack
LDF, # load function
AP, # function application
LD, # load a variable
CAR, # value of car cell
CDR, # value of cdr cell
DUM, # setup recursive closure list
RAP, # recursive apply
JOIN, # pop a list reference from the dump stack and set C to this value
RTN, # return from function
SEL, # logical selection (used to implement an if/then/else branch)
NULL, # test if list is empty
WRITEI, # write an integer to the terminal
WRITEC, # write a character to the terminal, e.g. 96 -> 'a'
READC, # read a single character from the terminal
READI, # read an integer from the terminal
STOP, # halt the machine
ZEROP, # test if top of stack is zero (does not consume the element) [nonstandard opcode]
GT0P, # test if top of stack is greater than zero (does not consume the element) [nonstandard opcode]
LT0P, # test if top of stack is less than zero (does not consume the element) [nonstandard opcode]
]
OP_CODES = dict([(op, True) for op in OP_CODES])
class SECD:
def __init__(self):
# Memory of the machine. A 'None' indicates an unused cell. Note that
# 0 is never used because that corresponds to nil.
self.memory = [None] + [None]*MAX_ADDRESS
self.max_used_address = 1
# By default WRITEI and WRITEC write to stdout.
self.output_stream = sys.stdout
self.input_stream = sys.stdin
self.debug = False
# Registers:
self.registers = {}
# The main stack:
self.registers['S'] = self.get_new_address()
self.set_nonterminal(self.registers['S'], 0, 0)
# The program counter; points to a memory location:
self.registers['C'] = -1 # initialised later
# The environment stack:
self.registers['E'] = self.get_new_address()
self.set_nonterminal(self.registers['E'], 0, 0)
# The dump stack:
self.registers['D'] = self.get_new_address()
self.set_nonterminal(self.registers['D'], 0, 0)
assert self.max_used_address < MAX_ADDRESS
def dump_registers(self):
"""
Dump to stdout the address of the registers S, E and D,
and the values of each. The register C (the program counter)
always stores an integer.
>>> m = SECD()
>>> m.dump_registers()
S: address = 2 value: []
E: address = 3 value: []
C: address = -1 value: -1
D: address = 4 value: []
>>> new_cell = m.get_new_address()
>>> m.set_int(new_cell, 123)
>>> m.push_stack('S', new_cell)
>>> m.dump_registers()
S: address = 6 value: [123]
E: address = 3 value: []
C: address = -1 value: -1
D: address = 4 value: []
"""
print 'S: address =', self.registers['S'], 'value:', self.get_value(self.registers['S'])
print 'E: address =', self.registers['E'], 'value:', self.get_value(self.registers['E'])
print 'C: address =', self.registers['C'], 'value:', self.registers['C']
print 'D: address =', self.registers['D'], 'value:', self.get_value(self.registers['D'])
def dump_memory(self):
"""
Dump to stdout each cell of the machine's memory, ignoring
cells that have not been used yet. Each line has two items:
the memory address (an integer) and the contents of the
cell, a tuple indicating the type (integer or nonterminal)
and the contents.
>>> m = SECD()
>>> m.dump_memory()
2 ('NT', 0, 0)
3 ('NT', 0, 0)
4 ('NT', 0, 0)
>>> new_cell = m.get_new_address()
>>> m.set_int(new_cell, 123)
>>> m.push_stack('S', new_cell)
>>> m.dump_memory()
2 ('NT', 0, 0)
3 ('NT', 0, 0)
4 ('NT', 0, 0)
5 ('INT', 123)
6 ('NT', 5, 2)
"""
for a in range(1, len(self.memory)):
if self.memory[a] is None: continue
print a, self.memory[a]
def get_new_address(self):
"""
Return the address of an unused memory cell.
>>> m = SECD()
>>> m.get_new_address()
5
>>> m.get_new_address()
6
"""
self.max_used_address += 1
assert self.max_used_address < MAX_ADDRESS, 'Error, out of memory.'
return self.max_used_address
def tag(self, address):
"""
All memory cells have a tag, indicating if the cell stores
an integers (TAG_INTEGER) or nonterminal (TAG_NONTERMINAL).
>>> m = SECD()
>>> new_cell = m.get_new_address()
>>> m.set_int(new_cell, 123)
>>> m.tag(new_cell)
'INT'
>>> new_cell = m.get_new_address()
>>> m.set_nonterminal(new_cell, 0, 0) # two nil pointers
>>> m.tag(new_cell)
'NT'
"""
return self.memory[address][0]
def push_stack(self, stack_name, new_cell):
"""
Push a cell onto the top of the given stack.
>>> m = SECD()
>>> m.get_value(m.registers['S'])
[]
>>> new_cell = m.get_new_address()
>>> m.set_int(new_cell, 123)
>>> m.push_stack('S', new_cell)
>>> m.get_value(m.registers['S'])
[123]
>>> new_cell = m.get_new_address()
>>> m.set_int(new_cell, 456)
>>> m.push_stack('S', new_cell)
>>> m.get_value(m.registers['S'])
[456, 123]
"""
new_head = self.get_new_address()
self.set_nonterminal(new_head, new_cell, self.registers[stack_name])
self.registers[stack_name] = new_head
def pop_stack(self, stack_name):
"""
Pop the top element off the stack.
>>> m = SECD()
>>> new_cell = m.get_new_address()
>>> m.set_int(new_cell, 123)
>>> m.push_stack('S', new_cell)
>>> new_cell = m.get_new_address()
>>> m.set_int(new_cell, 456)
>>> m.push_stack('S', new_cell)
>>> m.get_value(m.registers['S'])
[456, 123]
>>> m.pop_stack('S')
>>> m.get_value(m.registers['S'])
[123]
>>> m.pop_stack('S')
>>> m.get_value(m.registers['S'])
[]
"""
assert self.tag(self.registers[stack_name]) == TAG_NONTERMINAL
self.registers[stack_name] = self.cdr(self.registers[stack_name])
def car(self, address):
"""
Address register value of a nonterminal cell.
>>> m = SECD()
>>> new_cell = m.get_new_address()
>>> m.set_int(new_cell, 123)
>>> m.push_stack('S', new_cell)
>>> m.car(m.registers['S'])
5
>>> m.get_value(5)
123
"""
assert self.memory[address][0] == TAG_NONTERMINAL
return self.memory[address][1]
def cdr(self, address):
"""
Data register value of a nonterminal cell.
>>> m = SECD()
>>> new_cell = m.get_new_address()
>>> m.set_int(new_cell, 123)
>>> m.push_stack('S', new_cell)
>>> new_cell = m.get_new_address()
>>> m.set_int(new_cell, 456)
>>> m.push_stack('S', new_cell)
>>> m.get_value(m.registers['S'])
[456, 123]
>>> m.car(m.registers['S'])
7
>>> m.get_value(7)
456
>>> m.car(m.cdr(m.registers['S']))
5
>>> m.get_value(5)
123
"""
assert self.memory[address][0] == TAG_NONTERMINAL
return self.memory[address][2]
def set_int(self, address, x):
"""
Set a memory cell to store an integer. We cheat a little here
and allow a string to be stored in an integer cell as long
as it refers to an opcode.
>>> m = SECD()
>>> new_cell = m.get_new_address()
>>> m.set_int(new_cell, 123)
>>> m.memory[new_cell]
('INT', 123)
"""
assert type(x) == int or (type(x) == str and x in OP_CODES)
self.memory[address] = (TAG_INTEGER, x)
def get_int(self, address):
"""
Get the integer value of a memory cell.
>>> m = SECD()
>>> new_cell = m.get_new_address()
>>> m.set_int(new_cell, 123)
>>> m.get_int(new_cell)
123
"""
assert self.memory[address][0] == TAG_INTEGER
return self.memory[address][1]
def set_nonterminal(self, address, car_value, cdr_value):
"""
Set a nonterminal node.
>>> m = SECD()
>>> new_cell = m.get_new_address()
>>> m.set_nonterminal(new_cell, 100, 200)
>>> m.memory[new_cell]
('NT', 100, 200)
"""
self.memory[address] = (TAG_NONTERMINAL, car_value, cdr_value)
def store_py_list(self, address, x):
"""
Given the Python list x, store it in the machine's memory
at 'address' as a linked list. This function uses a basic
recursive definition so it will fail if x is too large (we
will hit Python's recursion limit).
>>> m = SECD()
>>> new_cell = m.get_new_address()
>>> m.store_py_list(new_cell, [])
>>> m.get_value(new_cell)
[]
>>> m.store_py_list(new_cell, [1])
>>> m.get_value(new_cell)
[1]
>>> m.store_py_list(new_cell, [1, 2, 3])
>>> m.get_value(new_cell)
[1, 2, 3]
>>> m.store_py_list(new_cell, [1, 2, []])
>>> m.get_value(new_cell)
[1, 2, []]
>>> m.store_py_list(new_cell, [[1, 2], [3], [[[4]]], 5])
>>> m.get_value(new_cell)
[[1, 2], [3], [[[4]]], 5]
>>> m.store_py_list(new_cell, [[], [[], []], [[[[ [], [], [[]] ]]]]])
>>> m.get_value(new_cell)
[[], [[], []], [[[[[], [], [[]]]]]]]
"""
if x == []:
self.memory[address] = (TAG_NONTERMINAL, 0, 0)
elif type(x[0]) == int or (type(x[0]) == str and x[0] in OP_CODES):
car_address = self.get_new_address()
cdr_address = self.get_new_address()
self.set_int(car_address, x[0])
self.store_py_list(cdr_address, x[1:])
self.set_nonterminal(address, car_address, cdr_address)
elif type(x[0]) == list:
car_address = self.get_new_address()
cdr_address = self.get_new_address()
self.store_py_list(car_address, x[0])
self.store_py_list(cdr_address, x[1:])
self.set_nonterminal(address, car_address, cdr_address)
else:
assert False, 'Unknown element type: %s' % (str(type(x[0])))
def get_value(self, address):
"""
Return a Python object representing the data stored at
'address'. We will either return an integer or a list. For
examples see store_py_list().
Note: this function is not the inverse of store_py_list()
due to the possible existence of cycles as created by the
DUM/RAP opcodes (note the case where '*** RECURSIVE LOOP ***'
is printed). Also, the nil pointer created by DUM will be
printed as 'NIL_PTR0', which is not handled by store_py_list().
>>> m = SECD()
>>> new_cell = m.get_new_address()
>>> m.set_int(new_cell, 33)
>>> m.get_value(new_cell)
33
>>> m.store_py_list(new_cell, [1, 2, 3])
>>> m.get_value(new_cell)
[1, 2, 3]
"""
# To avoid infinite loops we maintain a list of
# visited addresses.
self.seen_by_get_value = {}
return self._get_value(address)
def _get_value(self, address):
if address in self.seen_by_get_value:
return ['*** RECURSIVE LOOP ***']
self.seen_by_get_value[address] = True
if self.tag(address) == TAG_INTEGER:
return self.get_int(address)
elif self.tag(address) == TAG_NONTERMINAL:
if self.car(address) == 0 and self.cdr(address) == 0:
return []
elif self.car(address) == 0 and self.cdr(address) != 0:
# Special case constructed by DUM.
return ['NIL_PTR0'] + self._get_value(self.cdr(address))
else:
assert self.car(address) != 0
assert self.cdr(address) != 0
return [self._get_value(self.car(address))] + self._get_value(self.cdr(address))
else:
assert False, 'Unknown tag: %s' % self.tag(address)
def graph_at_address(self, address):
"""
Produce a dotty (graphviz) graph representing the linked structure at
'address'. See draw_graphs() for some examples and associated PNG plots.
>>> m = SECD()
>>> new_cell = m.get_new_address()
>>> m.store_py_list(new_cell, [])
>>> m.graph_at_address(new_cell).to_string().replace('\\n', '')
'digraph graphname {rankdir=LR;node5 [shape=record, label="<f0> 5|<f1> nil|<f2> nil"];}'
>>> m.store_py_list(new_cell, [1])
>>> m.graph_at_address(new_cell).to_string().replace('\\n', '')
'digraph graphname {rankdir=LR;node5 [shape=record, label="<f0> 5|<f1> car 6|<f2> cdr 7"];node5:f1 -> node6:f0;node5:f2 -> node7:f0;node6 [shape=record, label="<f0> 6|<f1> 1"];node7 [shape=record, label="<f0> 7|<f1> nil|<f2> nil"];}'
>>> m.store_py_list(new_cell, [1, 2, 3])
>>> m.graph_at_address(new_cell).to_string().replace('\\n', '')
'digraph graphname {rankdir=LR;node5 [shape=record, label="<f0> 5|<f1> car 8|<f2> cdr 9"];node5:f1 -> node8:f0;node5:f2 -> node9:f0;node8 [shape=record, label="<f0> 8|<f1> 1"];node9 [shape=record, label="<f0> 9|<f1> car 10|<f2> cdr 11"];node9:f1 -> node10:f0;node9:f2 -> node11:f0;node10 [shape=record, label="<f0> 10|<f1> 2"];node11 [shape=record, label="<f0> 11|<f1> car 12|<f2> cdr 13"];node11:f1 -> node12:f0;node11:f2 -> node13:f0;node12 [shape=record, label="<f0> 12|<f1> 3"];node13 [shape=record, label="<f0> 13|<f1> nil|<f2> nil"];}'
>>> m.store_py_list(new_cell, [1, 2, []])
>>> m.graph_at_address(new_cell).to_string().replace('\\n', '')
'digraph graphname {rankdir=LR;node5 [shape=record, label="<f0> 5|<f1> car 14|<f2> cdr 15"];node5:f1 -> node14:f0;node5:f2 -> node15:f0;node14 [shape=record, label="<f0> 14|<f1> 1"];node15 [shape=record, label="<f0> 15|<f1> car 16|<f2> cdr 17"];node15:f1 -> node16:f0;node15:f2 -> node17:f0;node16 [shape=record, label="<f0> 16|<f1> 2"];node17 [shape=record, label="<f0> 17|<f1> car 18|<f2> cdr 19"];node17:f1 -> node18:f0;node17:f2 -> node19:f0;node18 [shape=record, label="<f0> 18|<f1> nil|<f2> nil"];node19 [shape=record, label="<f0> 19|<f1> nil|<f2> nil"];}'
>>> m.store_py_list(new_cell, [[1, 2], [3], [[[4]]], 5])
>>> m.graph_at_address(new_cell).to_string().replace('\\n', '')
'digraph graphname {rankdir=LR;node5 [shape=record, label="<f0> 5|<f1> car 20|<f2> cdr 21"];node5:f1 -> node20:f0;node5:f2 -> node21:f0;node20 [shape=record, label="<f0> 20|<f1> car 22|<f2> cdr 23"];node20:f1 -> node22:f0;node20:f2 -> node23:f0;node22 [shape=record, label="<f0> 22|<f1> 1"];node23 [shape=record, label="<f0> 23|<f1> car 24|<f2> cdr 25"];node23:f1 -> node24:f0;node23:f2 -> node25:f0;node24 [shape=record, label="<f0> 24|<f1> 2"];node25 [shape=record, label="<f0> 25|<f1> nil|<f2> nil"];node21 [shape=record, label="<f0> 21|<f1> car 26|<f2> cdr 27"];node21:f1 -> node26:f0;node21:f2 -> node27:f0;node26 [shape=record, label="<f0> 26|<f1> car 28|<f2> cdr 29"];node26:f1 -> node28:f0;node26:f2 -> node29:f0;node28 [shape=record, label="<f0> 28|<f1> 3"];node29 [shape=record, label="<f0> 29|<f1> nil|<f2> nil"];node27 [shape=record, label="<f0> 27|<f1> car 30|<f2> cdr 31"];node27:f1 -> node30:f0;node27:f2 -> node31:f0;node30 [shape=record, label="<f0> 30|<f1> car 32|<f2> cdr 33"];node30:f1 -> node32:f0;node30:f2 -> node33:f0;node32 [shape=record, label="<f0> 32|<f1> car 34|<f2> cdr 35"];node32:f1 -> node34:f0;node32:f2 -> node35:f0;node34 [shape=record, label="<f0> 34|<f1> car 36|<f2> cdr 37"];node34:f1 -> node36:f0;node34:f2 -> node37:f0;node36 [shape=record, label="<f0> 36|<f1> 4"];node37 [shape=record, label="<f0> 37|<f1> nil|<f2> nil"];node35 [shape=record, label="<f0> 35|<f1> nil|<f2> nil"];node33 [shape=record, label="<f0> 33|<f1> nil|<f2> nil"];node31 [shape=record, label="<f0> 31|<f1> car 38|<f2> cdr 39"];node31:f1 -> node38:f0;node31:f2 -> node39:f0;node38 [shape=record, label="<f0> 38|<f1> 5"];node39 [shape=record, label="<f0> 39|<f1> nil|<f2> nil"];}'
"""
self.seen_by_graph_at_address = {} # avoid infinite loops
graph = pydot.Dot('graphname', graph_type='digraph', rankdir='LR')
self._graph_at_address(address, graph)
return graph
def _graph_at_address(self, address, graph):
if address in self.seen_by_graph_at_address:
return
else:
self.seen_by_graph_at_address[address] = True
if self.tag(address) == TAG_INTEGER:
graph.add_node(pydot.Node(name='node' + str(address),
label=pydot_record_string([str(address), str(self.get_int(address))]),
shape='record'))
elif self.tag(address) == TAG_NONTERMINAL:
if self.car(address) == 0 and self.cdr(address) == 0:
graph.add_node(pydot.Node(name='node' + str(address),
label=pydot_record_string([str(address), 'nil', 'nil']),
shape='record'))
else:
if self.car(address) == 0:
graph.add_node(pydot.Node(name='node' + str(address),
label=pydot_record_string([str(address), 'nil', str(self.cdr(address))]),
shape='record'))
graph.add_edge(pydot.Edge('node%d:f2' % address, 'node%d:f0' % self.cdr(address)))
self._graph_at_address(self.cdr(address), graph)
else:
graph.add_node(pydot.Node(name='node' + str(address),
label=pydot_record_string([str(address), ('car %d' % self.car(address)),
('cdr %d' % self.cdr(address))]),
shape='record'))
assert self.car(address) != 0
assert self.cdr(address) != 0
graph.add_edge(pydot.Edge('node%d:f1' % address, 'node%d:f0' % self.car(address)))
graph.add_edge(pydot.Edge('node%d:f2' % address, 'node%d:f0' % self.cdr(address)))
self._graph_at_address(self.car(address), graph)
self._graph_at_address(self.cdr(address), graph)
else:
assert False, 'Unknown tag: %s' % self.tag(address)
def load_program(self, code, stack=[]):
"""
Initialise the C register with 'code' and the stack S with 'stack'.
>>> s = SECD()
>>> s.load_program([ADD], [100, 42])
>>> s.get_value(s.registers['C'])
['ADD']
>>> s.get_value(s.registers['S'])
[100, 42]
"""
program = self.get_new_address()
self.store_py_list(program, code)
self.registers['C'] = program
self.store_py_list(self.registers['S'], stack)
self.running = True
def opcode_ADD(self):
"""
Integer addition; arguments are taken from the stack.
>>> s = SECD()
>>> s.load_program([ADD], [100, 42])
>>> s.execute_opcode()
>>> s.dump_registers()
S: address = 13 value: [142]
E: address = 3 value: []
C: address = 7 value: 7
D: address = 4 value: []
"""
assert self.get_int(self.car(self.registers['C'])) == ADD
val1 = self.get_int(self.car(self.registers['S']))
self.pop_stack('S')
val2 = self.get_int(self.car(self.registers['S']))
self.pop_stack('S')
result = self.get_new_address()
self.set_int(result, val1 + val2)
self.push_stack('S', result)
self.registers['C'] = self.cdr(self.registers['C'])
def opcode_SUB(self):
"""
Integer subtraction; arguments are taken from the stack.
>>> s = SECD()
>>> s.load_program([SUB], [100, 42])
>>> s.execute_opcode()
>>> s.dump_registers()
S: address = 13 value: [58]
E: address = 3 value: []
C: address = 7 value: 7
D: address = 4 value: []
"""
assert self.get_int(self.car(self.registers['C'])) == SUB
val1 = self.get_int(self.car(self.registers['S']))
self.pop_stack('S')
val2 = self.get_int(self.car(self.registers['S']))
self.pop_stack('S')
result = self.get_new_address()
self.set_int(result, val1 - val2)
self.push_stack('S', result)
self.registers['C'] = self.cdr(self.registers['C'])
def opcode_MUL(self):
"""
Integer multiplication; arguments are taken from the stack.
>>> s = SECD()
>>> s.load_program([MUL], [100, 42])
>>> s.execute_opcode()
>>> s.dump_registers()
S: address = 13 value: [4200]
E: address = 3 value: []
C: address = 7 value: 7
D: address = 4 value: []
"""
assert self.get_int(self.car(self.registers['C'])) == MUL
val1 = self.get_int(self.car(self.registers['S']))
self.pop_stack('S')
val2 = self.get_int(self.car(self.registers['S']))
self.pop_stack('S')
result = self.get_new_address()
self.set_int(result, val1*val2)
self.push_stack('S', result)
self.registers['C'] = self.cdr(self.registers['C'])
def opcode_DIV(self):
"""
Integer division; arguments are taken from the stack.
>>> s = SECD()
>>> s.load_program([DIV], [18, 3])
>>> s.execute_opcode()
>>> s.dump_registers()
S: address = 13 value: [6]
E: address = 3 value: []
C: address = 7 value: 7
D: address = 4 value: []
"""
assert self.get_int(self.car(self.registers['C'])) == DIV
val1 = self.get_int(self.car(self.registers['S']))
self.pop_stack('S')
val2 = self.get_int(self.car(self.registers['S']))
self.pop_stack('S')
result = self.get_new_address()
self.set_int(result, val1/val2)
self.push_stack('S', result)
self.registers['C'] = self.cdr(self.registers['C'])
def opcode_NIL(self):
"""
Push an empty list (nil) onto the stack. See also CONS.
>>> s = SECD()
>>> s.load_program([NIL], [18, 19])
>>> s.get_value(s.registers['S'])
[18, 19]
>>> s.execute_opcode()
>>> s.dump_registers()
S: address = 13 value: [[], 18, 19]
E: address = 3 value: []
C: address = 7 value: 7
D: address = 4 value: []
"""
assert self.get_int(self.car(self.registers['C'])) == NIL
new_cell = self.get_new_address()
self.set_nonterminal(new_cell, 0, 0)
self.push_stack('S', new_cell)
self.registers['C'] = self.cdr(self.registers['C'])
def opcode_LDC(self):
"""
Load a constant onto the stack. The constant expression
is whatever follows LDC in C, so it may be an arbitrary
s-expression.
>>> s = SECD()
>>> s.load_program([LDC, 3], [18, 19])
>>> s.execute_opcode()
>>> s.dump_registers()
S: address = 14 value: [3, 18, 19]
E: address = 3 value: []
C: address = 9 value: 9
D: address = 4 value: []
>>> s = SECD()
>>> s.load_program([LDC, [3, 4, [18]]], [1])
>>> s.execute_opcode()
>>> s.dump_registers()
S: address = 20 value: [[3, 4, [18]], 1]
E: address = 3 value: []
C: address = 9 value: 9
D: address = 4 value: []
"""
assert self.get_int(self.car(self.registers['C'])) == LDC
self.push_stack('S', self.car(self.cdr(self.registers['C'])))
self.registers['C'] = self.cdr(self.registers['C']) # skip LDC
self.registers['C'] = self.cdr(self.registers['C']) # skip the constant expression
def opcode_LDF(self):
"""
Builds a closure for the code immediately after LDF. The
function's parameters are to be found on the top of the
stack. Note that LDF doesn't start the execution of the
function - this happens when an appropriate AP opcode is
executed.
>>> s = SECD()
>>> s.load_program([LDC, [3, 4], LDF, [LD, [1, 2], LD, [1, 1], ADD, RTN], AP, WRITEI, STOP,], [500])
>>> s.store_py_list(s.registers['E'], [[99, 999]]) # pretend that this is the enclosing environment
>>> s.dump_registers()
S: address = 2 value: [500]
E: address = 3 value: [[99, 999]]
C: address = 5 value: 5
D: address = 4 value: []
Push [3, 4] onto the stack (these are the function's parameters):
>>> s.execute_opcode()
>>> s.dump_registers()
S: address = 52 value: [[3, 4], 500]
E: address = 3 value: [[99, 999]]
C: address = 9 value: 9
D: address = 4 value: []
Run LDF, which pushes the code portion onto the stack and
moves C to the code after the function:
>>> s.execute_opcode()
>>> s.dump_registers()
S: address = 53 value: [[['LD', [1, 2], 'LD', [1, 1], 'ADD', 'RTN'], [[99, 999]]], [3, 4], 500]
E: address = 3 value: [[99, 999]]
C: address = 17 value: 17
D: address = 4 value: []
>>> s.get_value(s.registers['C'])
['AP', 'WRITEI', 'STOP']
Execute AP, which saves a copy of the program counter, environment, and stack:
>>> s.execute_opcode()
>>> s.dump_registers()
S: address = 60 value: []
E: address = 61 value: [[3, 4], [99, 999]]
C: address = 16 value: 16
D: address = 59 value: [['WRITEI', 'STOP'], [[99, 999]], [500]]
Now we can execute the function itself:
>>> s.get_value(s.registers['C'])
['LD', [1, 2], 'LD', [1, 1], 'ADD', 'RTN']
>>> s.execute_opcode() # LD
>>> s.execute_opcode() # LD
>>> s.execute_opcode() # ADD
>>> s.execute_opcode() # RTN
>>> s.execute_opcode() # WRITEI
7
Now an example of a nested call. Evaluates (9*5) + (3+4) with the
multiplication happening during the LDF for the addition.
>>> mul_5_9 = [LDC, [5, 9], LDF, [LD, [1, 2], LD, [1, 1], MUL, RTN], AP]
>>> add_3_4 = [LDC, [3, 4], LDF, [LD, [1, 2], LD, [1, 1], ADD] + mul_5_9 + [ADD, RTN], AP, WRITEI, STOP]
>>> s = SECD()
>>> s.load_program(add_3_4, [500])
>>> s.store_py_list(s.registers['E'], [[99, 999]]) # pretend that this is the enclosing environment
Registers before the LDFs are executed:
>>> s.dump_registers()
S: address = 2 value: [500]
E: address = 3 value: [[99, 999]]
C: address = 5 value: 5
D: address = 4 value: []
>>> for _ in range(17): s.execute_opcode()
52
<BLANKLINE>
MACHINE HALTED!
<BLANKLINE>
Note that the original registers are preserved after the calls:
>>> s.dump_registers()
S: address = 2 value: [500]
E: address = 3 value: [[99, 999]]
C: address = 77 value: 77
D: address = 4 value: []
"""
assert self.get_int(self.car(self.registers['C'])) == LDF
# Make a note of the start of the original E list:
E_head = self.registers['E']
# The code after the LDF (the function itself):
code = self.car(self.cdr(self.registers['C']))
# The closure consists of code and E_head:
new_cell_0 = self.get_new_address()
new_cell_1 = self.get_new_address()
new_cell_2 = self.get_new_address()
new_cell_3 = self.get_new_address()
# Push the closure onto the stack:
self.set_nonterminal(new_cell_0, new_cell_1, self.registers['S'])
self.set_nonterminal(new_cell_1, code, new_cell_2)
self.set_nonterminal(new_cell_2, E_head, new_cell_3)
self.set_nonterminal(new_cell_3, 0, 0)
self.registers['S'] = new_cell_0
self.registers['C'] = self.cdr(self.registers['C']) # skip LDF
self.registers['C'] = self.cdr(self.registers['C']) # skip the code
def opcode_AP(self):
"""
Apply a function that has been loaded onto the stack using LDF.
First we save a copy of certain parts of S, E, and C on
the dump. We then clear S, set C to the start of the code
in the closure, and set E to the cons of the second element
on the original S (this will be the function parameters) and
the rest of E (which contains the environment that earlier
code may have set up).
For a full example and doctests, see opcode_LDF().
"""
assert self.get_int(self.car(self.registers['C'])) == AP
# We must save a copy of certain parts of S, E, and C on the dump
# before running the function's code.
# The cddr of S contains the stack after the closure and the function
# parameters. We save this on the dump.
if self.debug: print 'opcode_AP: saving this part of S: ', self.get_value(self.cdr(self.cdr(self.registers['S'])))
self.push_stack('D', self.cdr(self.cdr(self.registers['S'])))
# The environment E contains variable values specified by earlier
# code; after the function executes we want this to be restored to its
# original value.
if self.debug: print 'opcode_AP: saving E: ', self.get_value(self.registers['E'])
self.push_stack('D', self.registers['E'])
# The cdr of C is the instruction immediately after the AP, and we
# want to continue at that point after executing the function.
if self.debug: print 'opcode_AP: part of C to save: ', self.get_value(self.cdr(self.registers['C']))
self.push_stack('D', self.cdr(self.registers['C']))
closure_code = self.car(self.car(self.registers['S']))
closure_environment = self.car(self.cdr(self.car(self.registers['S'])))
second_element_of_S = self.car(self.cdr(self.registers['S']))
if self.debug:
print 'opcode_AP: closure_code:', self.get_value(closure_code)
print 'opcode_AP: closure_env: ', self.get_value(closure_environment)
print 'opcode_AP: 2nd element of S:', self.get_value(second_element_of_S)
# clear S:
self.registers['S'] = self.get_new_address()
self.store_py_list(self.registers['S'], [])
# set C to the code in the closure:
self.registers['C'] = closure_code
# set E to the cons of the second element in the original stack
# and the closure_environment
new_cell = self.get_new_address()
self.set_nonterminal(new_cell, second_element_of_S, closure_environment)
self.registers['E'] = new_cell
def opcode_JOIN(self):
"""
Return to a location specified by the top element of the
dump. Typically used in conjunction with SEL. For a longer
example see opcode_SEL().
>>> s = SECD()
>>> s.load_program([JOIN], [])
>>> new_cell = s.get_new_address()
>>> s.set_int(new_cell, 100)
>>> s.push_stack('D', new_cell)
>>> s.dump_registers()
S: address = 2 value: []
E: address = 3 value: []
C: address = 5 value: 5
D: address = 9 value: [100]
>>> s.execute_opcode()
>>> s.dump_registers()
S: address = 2 value: []
E: address = 3 value: []
C: address = 100 value: 100
D: address = 4 value: []
"""
assert self.get_int(self.car(self.registers['C'])) == JOIN
# Pop a value off the dump stack (a pointer):
assert self.car(self.registers['D']) != 0
new_C = self.get_int(self.car(self.registers['D']))
self.registers['D'] = self.cdr(self.registers['D'])
# Set the program counter to this new location
self.registers['C'] = new_C
def opcode_RTN(self):
"""
Return after a function application initiated using AP. We
recover the original S, E, and C registers from the dump,
and leave the function's result on the top of S.
>>> s = SECD()
>>> s.load_program([LDC, [3, 4], LDF, [LD, [1, 2], LD, [1, 1], ADD, RTN], AP, WRITEI, STOP,], [500])
>>> for _ in range(8): s.execute_opcode()
7
>>> s.dump_registers()
S: address = 2 value: [500]
E: address = 3 value: []
C: address = 41 value: 41
D: address = 4 value: []
Note that if the function puts more than one item onto the
stack S, only the top-most item is kept when the RTN is
executed. In this example we add 3 to 4 to get 7, then push
[9, 8, 7] onto the stack, and only the list [9, 8, 7] is
preserved after the RTN:
>>> s = SECD()
>>> s.load_program([LDC, [3, 4], LDF, [LD, [1, 2], LD, [1, 1], ADD, LDC, [9, 8, 7], RTN], AP, STOP,], [500])
>>> for _ in range(9): s.execute_opcode()
<BLANKLINE>
MACHINE HALTED!
<BLANKLINE>
>>> s.dump_registers()
S: address = 69 value: [[9, 8, 7], 500]
E: address = 3 value: []
C: address = 49 value: 49
D: address = 4 value: []
"""
assert self.get_int(self.car(self.registers['C'])) == RTN
# We pushed S, E, and C onto the dump, so they'll come off