-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathtim.src
3648 lines (3267 loc) · 132 KB
/
tim.src
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
% July 95: added Allyn Dimock's patches to include Gofer versions
H> module Tim where
H> import Utils
H> import Language
% $Date: 91/09/10 14:48:59 $
% $Revision: 1.9 $
% (c) 1991 Simon Peyton Jones & David Lester.
\chapter{TIM: the three instruction machine}
\label{sect:tim}
TIM\index{TIM},
the Three Instruction Machine, at first appears to be a very different
form of reduction machine from those we have seen so far. Nevertheless,
it turns out that we can transform a G-machine into a TIM in
a series of relatively simple steps.
In this chapter we describe these steps, thereby showing how the TIM works,
define a complete minimal
TIM compiler and evaluator, and then develop a sequence of improvements and
optimisations to it.
TIM was invented by Fairbairn and Wray, and their original paper \cite{FW87}
is well worth reading. It describes
TIM in a completely different way from the approach taken in this chapter.
The material developed in this chapter goes considerably beyond
Fairbairn and Wray's work, however, so the level of detail increases
in later sections where less well-known ideas are discussed and implemented.
Many of the new ideas presented are due to Guy Argo
and are presented in his FPCA paper
\cite{Argo89} and his Ph.D.\ thesis \cite{ArgoThesis}.
%Wakeling and Dix have also made a useful contribution
%\cite{WD89}.
\section{Background: How TIM works}
Consider the following function definition:
\begin{verbatim}
f x y = g E1 E2
\end{verbatim}
where @E1@ and @E2@ are arbitrary (and perhaps complex) expressions, and
@g@ is some other function.
Both the template instantiation machine (Chapter~\ref{sect:template})
and the G-machine (Chapter~\ref{sect:g-machine}) will perform
the following reduction:
\begin{verbatim}
@ reduces to @
/ \ / \
@ y @ E2
/ \ / \
f x g E1
\end{verbatim}
The G-machine will take quite a few (simple) instructions to do this, whereas
the template machine does it in one (complicated) step, but the
net result is the same.
In this picture, @E1@ and @E2@ are the {\em graphs of\/}
the expressions @E1@ and @E2@. For example, if @E1@ was @(x+y)*(x-y)@, the
first argument of @g@ would be a graph of @(x+y)*(x-y)@. This graph has to
be laboriously built in the heap (by code generated by
the ${\cal C}$ compilation scheme).
Sadly this might be wasted work, because
@g@ might discard its first argument without using it.
We would like to find some way of limiting the amount of graph-building
done for arguments to functions.
\subsection{Flattening\index{flattening}}
\label{sect:tim:flatten}
Step 1 of our transformation does just this. Suppose we replace the
definition of @f@ with the following new one:
\begin{verbatim}
f x y = g (c1 x y) (c2 x y)
c1 x y = E1
c2 x y = E2
\end{verbatim}
We have invented two auxiliary functions, @c1@ and @c2@.
This definition is plainly equivalent to the old one, but
{\em no matter how large or complicated @E1@ is, the only work done during
the @f@ reduction is to build the graph of @(c1 x y)@}.
Better still, for a G-machine implementation, there is a
further benefit which we get automatically.
With the first definition, @E1@ would be compiled by the ${\cal C}$
scheme; no advantage can be taken of the optimisations present in the
${\cal E}$ scheme when compiling arithmetic expressions.
But with the second definition, the expression @E1@ is now the right-hand
side of a supercombinator, so all these optimisations apply.
We can evaluate @(x+y)*(x-y)@ much more efficiently in this way.
Of course, @E1@ and @E2@ might themselves contain large expressions
which will get compiled with the ${\cal C}$ scheme (for example, suppose
@E2@ was @(h E3 E4)@), so we must apply the
transformation again to the right-hand sides of @c1@ and @c2@.
The result is a {\em flattened\/} program, so-called because
no expression has a nested structure.
\subsection{Tupling\index{tupling}}
The next observation is that both @c1@ and @c2@ are applied to both @x@ and
@y@, so we have to construct the graphs of @(c1 x y)@ and @(c2 x y)@ before
calling @g@. If @c1@ and @c2@ had lots of arguments, rather than just two,
the graphs could get quite big.
The two graphs are so similar to each other that
it is natural to ask whether these argument graphs
could share some common part to avoid
duplication, and thereby reduce heap allocation.
We can express this idea with a
second transformation:
\begin{verbatim}
f x y = let tup = (x,y)
in g (c1 tup) (c2 tup)
c1 (x,y) = E1
c2 (x,y) = E2
\end{verbatim}
The idea is that @f@ first packages up its arguments into a tuple, and
then passes this single tuple to @c1@ and @c2@.
With this definition of @f@, the @f@-reduction looks like this:
\begin{verbatim}
@ reduces to @
/ \ / \
@ y / @
/ \ @ / \
f x / \ c2 \
g @ \
/ \_____\
c1 \
-----
| -|---> x
-----
| -|---> y
-----
\end{verbatim}
\subsection{Spinelessness\index{spinelessness}}
Looking at the previous picture, you can see that {\em
the arguments pointed to
by the spine are always of the form @(c tup)@}, for some supercombinator
@c@ and tuple @tup@.
During reduction, we build up a stack of pointers to these arguments.
But since they are now all of the same form, we could instead stack
the (root of) the arguments themselves! So, after the @f@-reduction, the
stack would look like this:
\begin{verbatim}
| | |
|-------------- |
| c2 | ----|---\
|---------------| \ ---------------
| c1 | ------------> | | | x
|---------------| |-------------|
| | | y
---------------
\end{verbatim}
Each item on the spine stack\index{spine stack} is now
a pair of a code pointer and a pointer to a tuple.
You can think of this pair as an application node, the code defining a function
which is being applied to the tuple.
On entry to @f@, the (roots of the) arguments @x@ and @y@ were on the stack,
so the tuple of @x@ and @y@ is actually a tuple of code pointer/tuple pointer
pairs.
A code pointer/tuple pointer pair is called a {\em closure\index{closure}},
and a tuple
of such closures is called a {\em frame\index{frame}}.
A pointer to a frame is called
a {\em frame pointer\index{frame pointer}}.
Notice that there is no spine in the heap any more; the stack {\em is\/} the
spine of the expression being evaluated.
TIM is a spineless machine.
\subsection{An example}
\label{sect:tim:compose-eg}
It is time for an example of how a TIM program might work.
Consider the function @compose2@, defined like this:
\begin{verbatim}
compose2 f g x = f (g x x)
\end{verbatim}
The `flattened' form of @compose2@ would be
\begin{verbatim}
compose2 f g x = f (c1 g x)
c1 g x = g x x
\end{verbatim}
When @compose2@ is entered, its three arguments will be on top of the stack,
like this:
\begin{verbatim}
| | |
|---------------|
x | x-code| x-frm |
|---------------|
g | g-code| g-frm |
|---------------|
f | f-code| f-frm |
|---------------|
\end{verbatim}
The first thing to do is to form the tuple (frame)
of these three arguments in the
heap. We can then remove them from the stack. We will keep a pointer to the
new frame in a special register, called the {\em frame pointer}.
This is done by the instruction
\begin{verbatim}
Take 3
\end{verbatim}
The state of the machine now looks like this:
\begin{verbatim}
| | |
|---------------|
-----------------
Frame ptr ------------------------> f | f-code| f-frm |
|---------------|
g | g-code| g-frm |
|---------------|
x | x-code| x-frm |
-----------------
\end{verbatim}
Next, we have to prepare the arguments for @f@. There is only one, namely
@(g x x)@, and we want to push a
closure for it onto the stack. The frame pointer
for the closure is just the current frame pointer register, and so
the instruction need only supply a code label:
\begin{verbatim}
Push (Label "c1")
\end{verbatim}
Finally, we want to jump to @f@. Since @f@ is an argument to @compose@,
not a global supercombinator, @f@ is represented by a closure
in the current frame. What we must
do is fetch the closure,
load its frame pointer into the frame pointer register, and
its code pointer into the program counter.
This is done by the instruction:
\begin{verbatim}
Enter (Arg 1) -- f is argument 1
\end{verbatim}
After this instruction, the state of the machine is like this:
\begin{verbatim}
| | |
|---------------| -----------------
| c1 | ----|-----------> f | f-code| f-frm |
|---------------| |---------------|
g | g-code| g-frm |
Frame ptr: f-frm |---------------|
Program ctr: f-code x | x-code| x-frm |
-----------------
\end{verbatim}
That is it! The main body of @compose2@ consists of just these three
instructions:
\begin{verbatim}
compose2: Take 3 -- 3 arguments
Push (Label "c1") -- closure for (g x x)
Enter (Arg 1) -- f is argument 1
\end{verbatim}
We still need to deal with the label @c1@, though.
When the closure for @(g x x)@ is needed, it will be entered with the @Enter@
instruction, so that the program counter will point to @c1@, and the
frame pointer to the original frame containing @f@, @g@ and @x@.
At this point, all we need do is to prepare the argument for @g@, namely @x@,
and enter @g@:
\begin{verbatim}
c1: Push (Arg 3) -- x is argument 3
Push (Arg 3) -- x again
Enter (Arg 2) -- g is argument 2
\end{verbatim}
The @Push (Arg 3)@ instruction fetches a copy of the closure for @x@ from the
current frame, and pushes it onto the stack. Then the @Enter (Arg 2)@
instruction applies @g@ to the argument(s) now on the
stack\footnote{%
There might be more than just two if the stack was non-empty when the
@(g x x)@ closure was entered.}.
\subsection{Defining the machine with state transition rules}
You can see why it is called the Three Instruction Machine: there are
three dominant instructions: @Take@, @Push@ and @Enter@. In some ways,
it is rather optimistic to claim that it has only three instructions,
because @Push@ and @Enter@ both have
several `addressing modes'\index{addressing modes} and,
furthermore, we will need to invent quite a few
brand new instructions in due course. Still, it makes a nice name.
As usual, we use state transition rules\index{state transition rules}
to express the precise
effect of each instruction.
First of all we must define the {\em state\/} of the machine. It is
a quintuple:
\[
\mbox{\em (instructions, frame pointer, stack, heap, code store)}
\]
or $(i,f,s,h,c)$ for short.
The code store is the only item which has not already been described.
It contains a collection
of pieces of code, each of which has a label.
In practice, the code store contains the compiled supercombinator definitions,
each labelled with the name of the supercombinator, though in principle it
could also contain other labelled code fragments if that proved useful.
We now develop the transition rules for each of the instructions.
$@Take@~ n$ forms the top $n$ elements of the stack into a new frame, and
makes the current frame pointer point to it.
\timrule{
\timstate
{@Take@~n:i}
{f}
{c_1:\ldots:c_n:s}
{h} {c}
}{
\timstate
{i} {f'} {s}
{h[f':\langle c_1,\ldots,c_n \rangle]}
{c}
} \label{rule:take}
Now we come to the rules for @Push@ and @Enter@. These two instructions
have just the same addressing modes\index{addressing modes}
(@Arg@, @Label@ and so on), and
there is a very definite relationship between them,
which we dignify with a formal statement:
\begin{important}
{\em The @Push@/@Enter@ relationship.}
\index{Push/Enter relationship@@@Push@/@Enter@ relationship}
If the instruction $@Push@~arg$ pushes a closure $(i,f)$ onto the stack,
then $@Enter@~arg$ will load $i$ into the program counter and $f$ into
the current frame pointer.
\end{important}
The instruction
$@Push@~(@Arg@~ n)$ fetches the $n$th closure from the current frame, and
pushes it onto the stack.
\timrule{
\timstate
{@Push@\ (@Arg@\ k):i}
{f} {s}
{h[f:\langle (i_1,f_1),\ldots,(i_k,f_k),\ldots,(i_n,f_n) \rangle]}
{c}
}{
\timstate
{i} {f}
{(i_k,f_k):s}
{h} {c}
}
$@Push@~(@Label@~ l)$ looks up the label $l$ in the code store, and
pushes a closure consisting of this code pointer together with the
current frame pointer:
\timrule{
\timstate
{@Push@\ (@Label@\ l):i}
{f} {s} {h} {c[l:i']}
}{
\timstate
{i} {f}
{(i',f):s}
{h} {c}
}
In the @compose@ example, we had to invent an arbitrary label @c1@.
It is a nuisance having to invent these labels, and instead we will
simply
add a new form for the push instruction, $@Push (Code@~i@)@$, which makes the
target code sequence $i$ part of the instruction itself.
Thus, instead of
\begin{verbatim}
Push (Label "c1")
\end{verbatim}
we can write
\begin{verbatim}
Push (Code [Push (Arg 3), Push (Arg 3), Enter (Arg 2)])
\end{verbatim}
Here is the appropriate state transition rule:
\timrule{
\timstate
{@Push@\ (@Code@\ i'):i}
{f} {s} {h} {c}
}{
\timstate
{i} {f}
{(i',f):s}
{h} {c}
}
So far we have three `addressing modes'\index{addressing modes}:
@Arg@, @Code@, @Label@. We need
to add one more, @IntConst@, for integer constants. For example, the call
@(f 6)@ would compile to the code
\begin{verbatim}
Push (IntConst 6)
Enter (Label "f")
\end{verbatim}
The @Push@ instruction always pushes a closure (that is, a
code pointer/frame pointer pair)
onto the stack, but in the case of integer constants it is
not at all obvious what closure it should push.
Since we need somewhere to store
the integer\index{integer!representation in TIM}
itself, let us `steal' the frame pointer slot for that
purpose\footnote{%
We are making the implicit assumption
that an integer is no larger than a frame pointer, which
is usually true in practice.
}. This decision leads to the following rule, where @intCode@ is the
(as yet undetermined) code sequence for integer closures:
\timrule
{\timstate{@Push (IntConst@~n@)@:i}{f}{s}{h}{c}}
{\timstate{i}{f}{(@intCode@,n):s}{h}{c}}
\label{rule:intconst}
What should @intCode@ do? For the present our machine will do no arithmetic,
so an easy solution is to make @intCode@ the empty code sequence:
1> intCode = []
If an integer closure is ever entered, the machine will jump to the
empty code sequence, which will halt execution. This will allow us
to write programs which return integers, which is enough for Mark 1.
So much for the @Push@ instruction.
The rules for the @Enter@ instruction, one for each addressing mode,
follow directly from the @Push@/@Enter@ relationship:
\timrule{
\timstate
{[@Enter@\ (@Label@\ l)]}
{f} {s} {h} {c[l:i]}
}{
\timstate
{i} {f} {s} {h} {c}
}
\timrule{
\timstate
{[@Enter@\ (@Arg@\ k)]}
{f} {s}
{h[f:\langle (i_1,f_1),\ldots,(i_k,f_k),\ldots,(i_n,f_n) \rangle]}
{c}
}{
\timstate
{i_k} {f_k} {s} {h} {c}
}
\timrule{
\timstate
{[@Enter@\ (@Code@\ i)]}
{f} {s} {h} {c}
}{
\timstate
{i} {f}
{s}
{h} {c}
} \label{rule:tim:enter-code}
\timrule{
\timstate
{[@Enter@\ (@IntConst@\ n)]}
{f} {s} {h} {c}
}{
\timstate
{@intCode@} {n}
{s} {h} {c}
}
\subsection{Compilation}
We have now given a precise statement of what each TIM instruction does.
It remains to describe how to translate a program into TIM instructions.
This we do, as before, using a set of {\em compilation schemes}.
\index{compilation schemes}
Each supercombinator is compiled with the \tSC{} scheme, which is given
in Figure~\ref{fig:tim:schemes}.
The initial environment passed into \tSC{} binds each supercombinator name
to a @Label@ addressing mode for it.
The \tSC{} scheme just produces a
@Take@ instruction and invokes the \tR{} scheme, passing it an environment
augmented by bindings which say what addressing mode to use for each argument.
\begin{figure*}
$\begin{array}{|l|}
\hline
\\
\parbox{29pc}{
$\SC{def}~\rho$ is the TIM code for the supercombinator definition $def$,
in the environment $\rho$}
\\
\\
\begin{array}{rcll}
\SC{f\ x_1\ \ldots\ x_n\ @=@\ e}~\rho & = & @Take@\ n\ @:@\
\R{e}\ \rho[x_1 \mapsto @Arg@~1,\ldots,x_n \mapsto @Arg@~n] &
\end{array} \\
\\
\hline
\\
%
\parbox[t]{29pc}{
$\R{e}~\rho$ is TIM code which applies the value of the expression
$e$ in environment $\rho$ to the arguments on the stack.
}
\\
\\
\begin{array}{rcll}
\R{e_1~e_2}~\rho & = & @Push@~(\A{e_2}~\rho)~@:@~\R{e_1}~\rho & \\
%
\R{a}~\rho & = & @Enter@~(\A{a}~\rho) &
\mbox{where $a$ is an integer, variable,} \\
& & & \mbox{or supercombinator}
\end{array} \\
\\
\hline
\\
\parbox[t]{29pc}{
$\A{e}~\rho$ is a TIM addressing mode for expression $e$
in environment $\rho$.}
\\
\\
\begin{array}{rcll}
\A{x}~\rho & = & \rho~x &
\mbox{where $x$ is bound by $\rho$} \\
%
\A{n}~\rho & = & @IntConst@~ n &
\mbox{where $n$ is an integer} \\
%
\A{e}~\rho & = & @Code@~(\R{e}~\rho) & \mbox{otherwise}
\end{array} \\
\\
\hline
\end{array}$
\caption{The \tSC{}, \tR{} and \tA{} compilation schemes}
\label{fig:tim:schemes}
\end{figure*}
The \tR{} scheme (Figure~\ref{fig:tim:schemes})
simply pushes arguments onto the stack until it finds
a variable or supercombinator, which it enters.
It uses the \tA{} scheme to generate the
correct addressing mode. Notice the way that the flattening\index{flattening}
process
described in Section~\ref{sect:tim:flatten} is carried out `on the fly'
by these rules.
For the present, we omit arithmetic, data structures, case
analysis and @let(rec)@ expressions.
They will all be added later.
\subsection{Updating}
So far there has been no mention of updating\index{updates}.
That is because, now that
the spine has vanished, there are no spine nodes to update!
Indeed, the machine as so far described is a tree-reduction machine.
Shared arguments may be evaluated repeatedly.
Doing updates properly is the Achilles' heel of
spineless implementations. It is utterly necessary, because otherwise
an unbounded amount of work could be duplicated,
yet it adds complexity
which loses some of the elegance and speed (duplication aside)
of the non-updating version.
We will return to updating later in Section~\ref{sect:tim-updates},
but meanwhile it is enough to implement the non-updating version.
\section{Mark 1: A minimal TIM}
\label{minimal-tim}
\index{TIM!Mark 1}
In this section we will develop a minimal, but complete, TIM implementation,
without arithmetic, data structures or updates. These will be added
in subsequent sections.
\subsection{Overall structure}
The structure is much the same as for the template instantiation
interpreter.
The @run@ function is the composition of four functions, @parse@, @compile@,
@eval@ and @showResults@, just as before. The type of @parse@ is given in
Chapter~\ref{sect:language}; the types for the other three are given below:
M> run :: [char] -> [char]
M> compile :: coreProgram -> timState
M> eval :: timState -> [timState]
M> showResults :: [timState] -> [char]
GH> runProg :: [Char] -> [Char]
GH> compile :: CoreProgram -> TimState
GH> eval :: TimState -> [TimState]
GH> showResults :: [TimState] -> [Char]
>
M> run = showResults . eval . compile . parse
GH> runProg = showResults . eval . compile . parse
\par
It is often convenient to see all the intermediate states, so we
also provide @fullRun@, which uses @showFullResults@ to show each state:
M> fullRun :: [char] -> [char]
GH> fullRun :: [Char] -> [Char]
> fullRun = showFullResults . eval . compile . parse
We need to import the language module:
M> %include "language"
G> -- :a language.lhs -- parser data types
\subsection{Data type definitions}
The data type for TIM instructions corresponds directly to the instructions
introduced so far.
M1> instruction ::= Take num
M1> | Enter timAMode
M1> | Push timAMode
GH1> data Instruction = Take Int
GH1> | Enter TimAMode
GH1> | Push TimAMode
The type of addressing modes, @timAMode@,
is separated out as a distinct data type to stress the
relationship between @Push@ and @Enter@.
M1-4> timAMode ::= Arg num
M1-4> | Label [char]
M1-4> | Code [instruction]
M1-4> | IntConst num
GH1-4> data TimAMode = Arg Int
GH1-4> | Label [Char]
GH1-4> | Code [Instruction]
GH1-4> | IntConst Int
The state of the TIM machine is given by the following definition:
M1-4> timState == ([instruction], || The current instruction stream
M1-4> framePtr, || Address of current frame
M1-4> timStack, || Stack of arguments
M1-4> timValueStack, || Value stack (not used yet)
M1-4> timDump, || Dump (not used yet)
M1-4> timHeap, || Heap of frames
M1-4> codeStore, || Labelled blocks of code
M1-4> timStats) || Statistics
GH1-4> type TimState = ([Instruction], -- The current instruction stream
GH1-4> FramePtr, -- Address of current frame
GH1-4> TimStack, -- Stack of arguments
GH1-4> TimValueStack, -- Value stack (not used yet)
GH1-4> TimDump, -- Dump (not used yet)
GH1-4> TimHeap, -- Heap of frames
GH1-4> CodeStore, -- Labelled blocks of code
GH1-4> TimStats) -- Statistics
The value stack\index{value stack} and dump\index{dump}
are only required later on in this chapter, but it
is more convenient to add placeholders for them right away.
We consider the representation for each of these components in turn.
\begin{itemize}
\item
The {\em current instruction stream\/} is represented by a list of instructions.
In a real machine this would be the program counter together with
the program memory.
\item
The {\em frame pointer\/}\index{frame pointer} is usually the
address of a frame in the heap, but there are two other possibilities:
it might be used to hold an integer value, or it might be
uninitialised. The machine always `knows' which of these three
possibilities to expect, but it is
convenient in our implementation to distinguish them by using an
algebraic data type for @framePtr@:
M> framePtr ::= FrameAddr addr || The address of a frame
M> | FrameInt num || An integer value
M> | FrameNull || Uninitialised
GH> data FramePtr = FrameAddr Addr -- The address of a frame
GH> | FrameInt Int -- An integer value
GH> | FrameNull -- Uninitialised
If we do not do this, Miranda will (legitimately) complain
of a type error when we try to use an address as a number.
Furthermore, having a constructor for the uninitialised state @FrameNull@
means that our interpreter will discover if we ever mistakenly try to use
an uninitialised value as a valid address.
\item
The {\em stack\index{stack!in TIM\/}} contains {\em closures}, each of which is a
pair containing a code pointer and a frame pointer.
We represent the stack as a list.
M> timStack == [closure]
GH> type TimStack = [Closure]
M> closure == ([instruction], framePtr)
GH> type Closure = ([Instruction], FramePtr)
\item
The {\em value stack\/}\index{value stack!in TIM}
and {\em dump\/}\index{dump!in TIM} are not used at all to begin with,
so we represent each of them with a dummy algebraic data type which has
just one nullary constructor. Later we will replace these definitions
with more interesting ones.
M1> timValueStack ::= DummyTimValueStack
GH1> data TimValueStack = DummyTimValueStack
M1-3> timDump ::= DummyTimDump
GH1-3> data TimDump = DummyTimDump
\item
The {\em heap\/}\index{heap} contains
{\em frames}, each of which is a tuple of closures.
The data type of frames is important enough to merit
an abstract data type of its own.
M> timHeap == heap frame
GH> type TimHeap = Heap Frame
>
M> abstype frame
M> with fAlloc :: timHeap -> [closure] -> (timHeap, framePtr)
M> fGet :: timHeap -> framePtr -> num -> closure
M> fUpdate :: timHeap -> framePtr -> num -> closure -> timHeap
M> fList :: frame -> [closure] || Used when printing
GH> fAlloc :: TimHeap -> [Closure] -> (TimHeap, FramePtr)
GH> fGet :: TimHeap -> FramePtr -> Int -> Closure
GH> fUpdate :: TimHeap -> FramePtr -> Int -> Closure -> TimHeap
GH> fList :: Frame -> [Closure] -- Used when printing
These operations allow frames to be built, and components to
be extracted and updated.
The first element of the list given to @fAlloc@ is numbered @1@ for
the purposes of @fGet@ and @fUpdate@.
Here is a simple implementation based on lists.
M> frame == [closure]
GH> type Frame = [Closure]
>
> fAlloc heap xs = (heap', FrameAddr addr)
> where
> (heap', addr) = hAlloc heap xs
>
M> fGet heap (FrameAddr addr) n = f ! (n-1) || Miranda's ! operator
M> || uses zero indexing
GH> fGet heap (FrameAddr addr) n = f !! (n-1)
> where
> f = hLookup heap addr
>
> fUpdate heap (FrameAddr addr) n closure
> = hUpdate heap addr new_frame
> where
> frame = hLookup heap addr
> new_frame = take (n-1) frame ++ [closure] ++ drop n frame
>
> fList f = f
\item
For each label, the {\em code store\/} gives the corresponding compiled code:
M1-5> codeStore == assoc name [instruction]
GH1-5> type CodeStore = ASSOC Name [Instruction]
We take the opportunity to provide a lookup function for
labels, which generates an error message if it fails:
M1-5> codeLookup :: codeStore -> name -> [instruction]
GH1-5> codeLookup :: CodeStore -> Name -> [Instruction]
1-5> codeLookup cstore l
1-5> = aLookup cstore l (error ("Attempt to jump to unknown label "
1-5> ++ show l))
\item
As usual, we make the {\em statistics\/} into an abstract data type which we
can add to easily:
M> abstype timStats
M> with statInitial :: timStats
M> statIncSteps :: timStats -> timStats
M> statGetSteps :: timStats -> num
GH> statInitial :: TimStats
GH> statIncSteps :: TimStats -> TimStats
GH> statGetSteps :: TimStats -> Int
\end{itemize}
The first implementation, which counts only the number of steps,
is rather simple:
M> timStats == num || The number of steps
GH> type TimStats = Int -- The number of steps
> statInitial = 0
> statIncSteps s = s+1
> statGetSteps s = s
Finally, we need the code for heaps and stacks:
M> %include "utils"
GH> -- :a util.lhs -- heap data type and other library functions
\subsection{Compiling a program}
\label{sect:tim:compiler}
@compile@ works very much like the template instantiation compiler,
creating an initial machine state from the program it is given.
The main difference lies in the compilation function @compileSC@ which
is applied to each supercombinator.
1-4> compile program
M1-4> = ([Enter (Label "main")], || Initial instructions
M1-4> FrameNull, || Null frame pointer
M1-4> initialArgStack, || Argument stack
M1-4> initialValueStack, || Value stack
M1-4> initialDump, || Dump
M1-4> hInitial, || Empty heap
M1-4> compiled_code, || Compiled code for supercombinators
M1-4> statInitial) || Initial statistics
GH1-4> = ([Enter (Label "main")], -- Initial instructions
GH1-4> FrameNull, -- Null frame pointer
GH1-4> initialArgStack, -- Argument stack
GH1-4> initialValueStack, -- Value stack
GH1-4> initialDump, -- Dump
GH1-4> hInitial, -- Empty heap
GH1-4> compiled_code, -- Compiled code for supercombinators
GH1-4> statInitial) -- Initial statistics
1-4> where
1-4> sc_defs = preludeDefs ++ program
1-4> compiled_sc_defs = map (compileSC initial_env) sc_defs
1-4> compiled_code = compiled_sc_defs ++ compiledPrimitives
1-4> initial_env = [(name, Label name) | (name, args, body) <- sc_defs]
1-4> ++ [(name, Label name) | (name, code) <- compiledPrimitives]
For the moment, the argument stack is initialised to be empty.
1> initialArgStack = []
For now the value stack and dump are initialised to their dummy values. Later
we will change these definitions.
1> initialValueStack = DummyTimValueStack
1-3> initialDump = DummyTimDump
\par
\sloppy
The compiled supercombinators, @compiled_sc_defs@, is obtained by compiling
each of the supercombinators in the program, using @compileSC@.
The initial environment passed to @compileSC@ gives a suitable addressing
mode for each supercombinator.
The code store, @compiled_code@, is obtained by combining @compiled_sc_defs@
with @compiledPrimitives@. The latter is intended to contain compiled
code for built-in primitives, but it is empty for the present:
> compiledPrimitives = []
Unlike the template machine and the G-machine, the initial heap is empty.
The reason for a non-empty initial heap in those cases was to retain sharing
for CAFs\index{CAF} (that is, supercombinators with no arguments
-- Section~\ref{sect:caf}).
In this initial version of the TIM machine, the compiled TIM code for a CAF
will be executed each time it is called, so the work
of evaluating the CAF is not shared. We will address this problem much later,
in Section~\ref{sect:tim:caf}.
The heart of the compiler is a direct translation of the compilation
schemes \tSC{}, \tR{} and \tA{} into the functions
@compileSC@, @compileR@ and @compileA@ respectively.
The environment, $\rho$, is represented by an association list binding
names to addressing modes. The G-machine compiler used a mapping from
names to stack offsets, but the extra flexibility of using
addressing modes turns out to be rather useful.
M> timCompilerEnv == [(name, timAMode)]
GH> type TimCompilerEnv = [(Name, TimAMode)]
\par
Now we are ready to define @compileSC@:
M> compileSC :: timCompilerEnv -> coreScDefn -> (name, [instruction])
GH> compileSC :: TimCompilerEnv -> CoreScDefn -> (Name, [Instruction])
1-2> compileSC env (name, args, body)
M1-2> = (name, Take (#args) : instructions)
GH1-2> = (name, Take (length args) : instructions)
1-2> where
1-2> instructions = compileR body new_env
1-2> new_env = (zip2 args (map Arg [1..])) ++ env
@compileR@ takes an expression and an environment, and delivers a list
of instructions:
M1-2> compileR :: coreExpr -> timCompilerEnv -> [instruction]
GH1-2> compileR :: CoreExpr -> TimCompilerEnv -> [Instruction]
1> compileR (EAp e1 e2) env = Push (compileA e2 env) : compileR e1 env
1> compileR (EVar v) env = [Enter (compileA (EVar v) env)]
1> compileR (ENum n) env = [Enter (compileA (ENum n) env)]
1> compileR e env = error "compileR: can't do this yet"
M1-2> compileA :: coreExpr -> timCompilerEnv -> timAMode
GH1-2> compileA :: CoreExpr -> TimCompilerEnv -> TimAMode
1-2> compileA (EVar v) env = aLookup env v (error ("Unknown variable " ++ v))
1-2> compileA (ENum n) env = IntConst n
1-2> compileA e env = Code (compileR e env)
\subsection{The evaluator}
Next we need to define how the evaluator actually works.
The definition of
@eval@ is exactly as for the template instantiation machine:
> eval state
M> = state : rest_states where
M> rest_states = [], timFinal state
M> = eval next_state, otherwise
M> next_state = doAdmin (step state)
GH> = state : rest_states where
GH> rest_states | timFinal state = []
GH> | otherwise = eval next_state
GH> next_state = doAdmin (step state)
>
> doAdmin state = applyToStats statIncSteps state
The @timFinal@ function says when a state is a final state.
We could invent a @Stop@ instruction, but it
is just as easy
to say that we have finished when the code sequence is empty:
1-4> timFinal ([], frame, stack, vstack, dump, heap, cstore, stats) = True
1-4> timFinal state = False
The @applyToStats@ function just applies a function to the
statistics component of the state:
1-4> applyToStats stats_fun (instr, frame, stack, vstack,
1-4> dump, heap, cstore, stats)
1-4> = (instr, frame, stack, vstack, dump, heap, cstore, stats_fun stats)
\subsubsection{Taking a step}
@step@ does the case analysis which takes a single instruction and
executes it. The @Take@ equation is a
straightforward transliteration of the corresponding state transition rule
(\ref{rule:take}):
1> step ((Take n:instr), fptr, stack, vstack, dump, heap, cstore,stats)
M1> = (instr, fptr', drop n stack, vstack, dump, heap', cstore, stats), #stack >= n
GH1> | length stack >= n = (instr, fptr', drop n stack, vstack, dump, heap', cstore, stats)
M1> = error "Too few args for Take instruction", otherwise
GH1> | otherwise = error "Too few args for Take instruction"
1> where (heap', fptr') = fAlloc heap (take n stack)
The equations for @Enter@ and @Push@ take advantage of the @Push@/@Enter@
relationship\index{Push/Enter relationship@@@Push@/@Enter@ relationship}
by using a common function @amToClosure@ which converts
a @timAMode@ to a closure:
1> step ([Enter am], fptr, stack, vstack, dump, heap, cstore, stats)
1> = (instr', fptr', stack, vstack, dump, heap, cstore, stats)
1> where (instr',fptr') = amToClosure am fptr heap cstore
1> step ((Push am:instr), fptr, stack, vstack, dump, heap, cstore, stats)
1> = (instr, fptr, amToClosure am fptr heap cstore : stack,
1> vstack, dump, heap, cstore, stats)
@amToClosure@ delivers the closure addressed by the addressing mode
which is its first argument:
M1-4> amToClosure :: timAMode -> framePtr -> timHeap -> codeStore -> closure
GH1-4> amToClosure :: TimAMode -> FramePtr -> TimHeap -> CodeStore -> Closure
1-4> amToClosure (Arg n) fptr heap cstore = fGet heap fptr n
1-4> amToClosure (Code il) fptr heap cstore = (il, fptr)
1-4> amToClosure (Label l) fptr heap cstore = (codeLookup cstore l, fptr)
1-4> amToClosure (IntConst n) fptr heap cstore = (intCode, FrameInt n)
\subsection{Printing the results}
As with the template instantiation version we need a rather boring
collection of functions to print the results in a sensible way.
It is often useful to print out the supercombinator definitions, so
@showResults@ begins by doing so, using the definitions in the first
state:
> showFullResults states
> = iDisplay (iConcat [
> iStr "Supercombinator definitions", iNewline, iNewline,
> showSCDefns first_state, iNewline, iNewline,
> iStr "State transitions", iNewline,
> iLayn (map showState states), iNewline, iNewline,
> showStats (last states)
> ])
> where
> (first_state:rest_states) = states
@showResults@ just shows the last state and some statistics:
1-4> showResults states
1-4> = iDisplay (iConcat [
1-4> showState last_state, iNewline, iNewline, showStats last_state
1-4> ])
1-4> where last_state = last states
\par
The rest of the functions are straightforward. @showSCDefns@ displays
the code for each supercombinator.
M> showSCDefns :: timState -> iseq
GH> showSCDefns :: TimState -> Iseq
1-4> showSCDefns (instr, fptr, stack, vstack, dump, heap, cstore, stats)
1-4> = iInterleave iNewline (map showSC cstore)
M> showSC :: (name, [instruction]) -> iseq
GH> showSC :: (Name, [Instruction]) -> Iseq
> showSC (name, il)
> = iConcat [
> iStr "Code for ", iStr name, iStr ":", iNewline,
> iStr " ", showInstructions Full il, iNewline, iNewline