-
Notifications
You must be signed in to change notification settings - Fork 1
/
MachInterp.lhs
1638 lines (1462 loc) · 63.4 KB
/
MachInterp.lhs
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
% -*- LaTeX -*-
% $Id: MachInterp.lhs 3206 2016-06-07 07:17:22Z wlux $
%
% Copyright (c) 1998-2016, Wolfgang Lux
% See LICENSE for the full license.
%
\nwfilename{MachInterp.lhs}
\section{An Interpreter for the Abstract Machine}
This section describes an interpreter for the abstract machine code in
Haskell.
\input{MachTypes.lhs} % \subsection{Basic Types}
\subsection{The Interpreter State Transformers}
For every abstract machine instruction, we implement a corresponding
interpreter function. All these function are based on a kind of
``micro-code'' state transformer.
\begin{verbatim}
> module MachInterp where
> import MachTypes
> import MachNode
> import MachStack
> import MachEnviron
> import MachChoice
> import MachSpace
> import MachThreads
> import MachResult
> import Char
> import Env
> import Monad
> import Combined
> import IO
\end{verbatim}
\subsubsection{Creating Nodes}
A \texttt{return} statement returns a fresh node to the calling
context.
\begin{verbatim}
> returnNode :: (NodePtr -> MachStateT ()) -> Instruction
> returnNode init =
> do
> ptr <- read'updateState (allocNode (error "Uninitialized result"))
> init ptr
> retNode ptr
> retNode :: NodePtr -> Instruction
> retNode ptr = updateState (pushNode ptr) >> ret
\end{verbatim}
A \texttt{let} statement allocates and initializes a group of nodes.
In order to handle mutually recursive nodes, allocation and
initialization of nodes are separated.
\begin{verbatim}
> letNodes :: [(String,NodePtr -> MachStateT ())] -> Instruction -> Instruction
> letNodes allocs next =
> do
> ptrs <- read'updateState (allocNodes (map uninitialized vs))
> updateState (setVars vs ptrs)
> zipWithM_ (initNode . snd) allocs ptrs
> next
> where vs = map fst allocs
> initNode init ptr = init ptr
> uninitialized v = error ("Uninitialized node " ++ show v)
> initChar :: Char -> NodePtr -> MachStateT ()
> initChar c ptr = updateNode ptr (CharNode c)
> initInt :: Integer -> NodePtr -> MachStateT ()
> initInt i ptr = updateNode ptr (IntNode i)
> initFloat :: Double -> NodePtr -> MachStateT ()
> initFloat f ptr = updateNode ptr (FloatNode f)
> initConstr :: NodeTag -> [String] -> NodePtr -> MachStateT ()
> initConstr (ConstructorTag t c n) vs ptr
> | length vs == n =
> readState (getVars vs) >>= updateNode ptr . ConstructorNode t c
> | otherwise = fail "Type error in initConstr"
> initClosure :: Function -> [String] -> NodePtr -> MachStateT ()
> initClosure (f,code,n) vs ptr
> | length vs <= n =
> readState (getVars vs) >>= updateNode ptr . ClosureNode f n code
> | otherwise = fail "Type error in initClosure"
> initLazy :: Function -> [String] -> NodePtr -> MachStateT ()
> initLazy (f,code,n) vs ptr
> | length vs == n =
> readState (getVars vs) >>= updateNode ptr . LazyNode f n code
> | otherwise = fail "Type error in initLazy"
> initFree :: NodePtr -> MachStateT ()
> initFree ptr = updateNode ptr (VarNode [] [])
> initIndir :: String -> NodePtr -> MachStateT ()
> initIndir v ptr = readState (getVar v) >>= updateNode ptr . IndirNode
> initQueueMe :: NodePtr -> MachStateT ()
> initQueueMe ptr = updateNode ptr (QueueMeNode [])
\end{verbatim}
As a matter of convenience, we also provide some allocation functions,
which initialize fresh nodes directly.
\begin{verbatim}
> allocChar :: Char -> MachStateT NodePtr
> allocChar c = read'updateState (allocNode (CharNode c))
> allocInt :: Integer -> MachStateT NodePtr
> allocInt i = read'updateState (allocNode (IntNode i))
> allocFloat :: Double -> MachStateT NodePtr
> allocFloat f = read'updateState (allocNode (FloatNode f))
> allocData :: Int -> String -> [NodePtr] -> MachStateT NodePtr
> allocData t c ptrs = read'updateState (allocNode (ConstructorNode t c ptrs))
> allocVariables :: Int -> MachStateT [NodePtr]
> allocVariables n = read'updateState (allocNodes (replicate n (VarNode [] [])))
> allocClosure :: Function -> [NodePtr] -> MachStateT NodePtr
> allocClosure (f,code,n) ptrs
> | length ptrs <= n =
> read'updateState (allocNode (ClosureNode f n code ptrs))
> | otherwise = fail "Type error in allocClosure"
> allocLazy :: Function -> [NodePtr] -> MachStateT NodePtr
> allocLazy (f,code,n) ptrs
> | length ptrs == n = read'updateState (allocNode (LazyNode f n code ptrs))
> | otherwise = fail "Type error in allocLazy"
\end{verbatim}
\subsubsection{Evaluation of Nodes}
An \texttt{eval} statement starts the evaluation of the referenced
node to weak head normal form. When the node is already in weak head
normal form it is returned to the caller. If the node is a lazy
application, it will be overwritten with a queue-me node that is later
overwritten with the result of the application. If the node is a
global application, the current search is suspended and the global
node is evaluated by the enclosing computation.
\begin{verbatim}
> enter :: String -> Instruction
> enter v = readState (getVar v) >>= enter
> where enter ptr = deref ptr >>= enterNode ptr
> enterNode _ (ClosureNode _ n code ptrs)
> | length ptrs == n =
> do
> updateState (pushNodes ptrs)
> code
> enterNode ptr lazy@(LazyNode f n code ptrs)
> | length ptrs == n =
> do
> updateState (saveBinding ptr lazy)
> updateNode ptr (QueueMeNode [])
> updateState (pushNode ptr)
> updateState (pushCont update)
> updateState (pushNodes ptrs)
> code
> | otherwise = fail "Wrong number of arguments in lazy application"
> enterNode ptr lazy@(QueueMeNode wq) =
> do
> thd <- readState (suspendThread (resume ptr))
> updateState (saveBinding ptr lazy)
> updateNode ptr (QueueMeNode (thd:wq))
> switchContext
> enterNode _ (IndirNode ptr) = deref ptr >>= enterNode ptr
> enterNode ptr lazy@(GlobalAppNode _ _) =
> suspendSearch ptr lazy (resume ptr)
> enterNode ptr _ = retNode ptr
> resume ptr = deref ptr >>= resumeNode ptr
> resumeNode _ (LazyNode _ _ _ _) =
> fail "Indirection to unevaluated lazy application node"
> resumeNode _ (QueueMeNode _) =
> fail "Indirection to locked lazy application node"
> resumeNode _ (IndirNode ptr) = deref ptr >>= resumeNode ptr
> resumeNode ptr _ = retNode ptr
> update = read'updateState popNodes2 >>= uncurry update'
> update' ptr lptr = deref lptr >>= updateLazy ptr lptr
> updateLazy ptr lptr lazy@(QueueMeNode wq) =
> do
> updateState (saveBinding lptr lazy)
> updateNode lptr (IndirNode ptr)
> updateState (pushNode ptr)
> updateState (wakeThreads wq)
> ret
> updateLazy _ _ (LazyNode _ _ _ _) =
> fail "Unlocked lazy application in update frame"
> updateLazy _ _ _ = fail "No lazy application in update frame"
\end{verbatim}
\subsubsection{Function Evaluation}
A call to a known function pushes the arguments onto the data stack
and enters the specified function. Upon entry, the called function
initializes a fresh local environment with the nodes from the data
stack and then executes its code. At the end, the function returns to
the current context from either the return or the update stack. If
both stacks are empty, the current thread terminates which eventually
may cause a deadlock.
\begin{verbatim}
> exec :: Function -> [String] -> Instruction
> exec (_,code,n) vs
> | length vs == n =
> do
> readState (getVars vs) >>= updateState . pushNodes
> code
> | otherwise = fail "Wrong number of arguments in Exec"
> entry :: [String] -> Instruction -> Instruction
> entry vs body =
> do
> updateState initEnv
> read'updateState (popNodes (length vs)) >>= updateState . setVars vs
> body
> ret :: Instruction
> ret = read'updateState popCont >>= maybe switchContext id
> switchContext :: Instruction
> switchContext = read'updateState runThread >>= maybe deadlock id
> where deadlock = readState curContext >>= deadlock'
> deadlock' IOContext = readState (return . Just)
> deadlock' GlobalContext = readState (return . Just)
> deadlock' _ = stoppedSearch
\end{verbatim}
When an unknown function is called (via a partial application node),
the machine must compare the number of arguments supplied in the call
with the arity of the called function. If too few arguments are
supplied, a new partial application node is allocated and returned to
the caller. Otherwise, the function is entered after pushing the
arguments onto the stack. If too many arguments are supplied, an
additional return frame is pushed onto the stack as well, which takes
care of applying the result of the application to the remaining
arguments.
\begin{verbatim}
> apply :: String -> [String] -> Instruction
> apply v vs =
> do
> ptrs <- readState (getVars vs)
> switchRigid v [(ClosureTag,applyPtr ptrs)]
> (const (fail "Type error in Apply: not a function"))
> where applyPtr ptrs ptr = deref ptr >>= applyNode ptrs
> applyNode ptrs' (ClosureNode f n code ptrs) =
> applyClosure f code n (ptrs ++ ptrs')
> applyClosure f code n ptrs
> | length ptrs < n = allocClosure (f,code,n) ptrs >>= retNode
> | otherwise =
> do
> let (ptrs',ptrs'') = splitAt n ptrs
> unless (null ptrs'')
> (updateState (pushNodes ptrs'') >>
> updateState (pushCont (applyCont (length ptrs''))))
> updateState (pushNodes ptrs')
> code
> applyCont n = entry ("_f" : xs) $ apply "_f" xs
> where xs = ['x':show i | i <- [1..n]]
\end{verbatim}
\texttt{Ccall} statements are intended for implementing calls to
foreign primitives written in C. We emulate such calls here by mapping
them onto a set of predefined functions (defined in
Sect.~\ref{sec:mach-arithmetic}).
\begin{verbatim}
> type Primitive = (String,[NodePtr] -> MachStateT NodePtr)
> cCall :: Primitive -> [String] -> Instruction
> cCall (_,code) vs = readState (getVars vs) >>= code >>= retNode
> prim1 :: Monad m => (NodePtr -> m a) -> [NodePtr] -> m a
> prim1 code [ptr] = code ptr
> prim1 _ _ = fail "Wrong number of arguments in CCall"
> prim2 :: Monad m => (NodePtr -> NodePtr -> m a) -> [NodePtr] -> m a
> prim2 code [ptr1,ptr2] = code ptr1 ptr2
> prim2 _ _ = fail "Wrong number of arguments in CCall"
\end{verbatim}
\subsubsection{Case Selection}
A \texttt{switch} statement selects the code branch matched by
the tag of the specified node. Depending on the mode of the switch
statement, an unbound variable either suspends the current thread
until the variable is instantiated (\texttt{rigid}) or instantiates
the variable non-deterministically (\texttt{flex}). If no case
matches, the default action is chosen. Global variables are never
instantiated. Instead, the current search is suspended until the
variable is instantiated in the enclosing computation.
After instantiating a variable, the abstract machine checks that all
constraints on the variable are still entailed and then wakes all
threads from the variable's wait queue. If the variable is bound to
another variable, the wait queues are concatenated instead of waking
the suspended threads. In addition, we must check the constraints of
the other variable as well because both constraint lists can include a
disequality between the variables. If a variable is bound to a global
variable and the local variable has constraints or blocked threads, we
must suspend the current search until the global variable is
instantiated.
Note that \texttt{bindVar} must check whether the variable node has
been bound already. This may happen if a search strategy restricts the
search space of a goal by instantiating the goal variable to a
non-variable term. For instance, in
\begin{verbatim}
main = concatMap try (map (`inject` nonNull) (try goal))
goal xs = length xs =:= 1
nonNull (_:_) = True
\end{verbatim}
the goal variable is bound to a list node before the search
continuations are resumed that were returned by the inner \texttt{try}
application.
\begin{verbatim}
> switchRigid :: String -> [(NodeTag,NodePtr -> Instruction)]
> -> (NodePtr -> Instruction) -> Instruction
> switchRigid v dispatchTable dflt = rigidSwitch
> where rigidSwitch = switch v dispatchTable' dflt
> dispatchTable' =
> (VariableTag,delay rigidSwitch) :
> (GlobalVarTag,delaySearch rigidSwitch) :
> dispatchTable
> delay :: Instruction -> NodePtr -> Instruction
> delay cont vptr = deref vptr >>= delayNode vptr
> where delayNode vptr var@(VarNode cs wq) =
> do
> thd <- readState (suspendThread cont)
> updateState (saveBinding vptr var)
> updateNode vptr (VarNode cs (thd:wq))
> switchContext
> switchFlex :: String -> [(NodeTag,NodePtr -> Instruction)]
> -> (NodePtr -> Instruction) -> Instruction
> switchFlex v dispatchTable dflt = flexSwitch
> where flexSwitch = switch v dispatchTable' dflt
> dispatchTable'
> | null alts = dispatchTable
> | otherwise =
> (VariableTag,tryBind alts flexSwitch) :
> (GlobalVarTag,delaySearch flexSwitch) :
> dispatchTable
> alts = map instantiate dispatchTable
> tryBind :: [NodePtr -> Instruction] -> Instruction -> NodePtr -> Instruction
> tryBind (alt:alts) cont vptr = deref vptr >>= tryBindNode vptr
> where tryBindNode vptr var@(VarNode cs wq)
> | null alts = alt vptr
> | otherwise =
> do
> thd <- read'updateState (yieldSuspendThread (resume vptr))
> case thd of
> Just thd ->
> do
> updateState (saveBinding vptr var)
> updateNode vptr (VarNode cs (thd:wq))
> switchContext
> Nothing -> choice vptr
> resume ptr = deref ptr >>= resumeNode ptr
> resumeNode _ (IndirNode ptr) = resume ptr
> resumeNode ptr (VarNode _ _) = choice ptr
> resumeNode _ _ = cont
> choice vptr = tryChoice (map ($ vptr) (alt:alts))
> delaySearch :: Instruction -> NodePtr -> Instruction
> delaySearch cont vptr = deref vptr >>= flip (suspendSearch vptr) cont
> instantiate ::(NodeTag,NodePtr -> Instruction) -> NodePtr -> Instruction
> instantiate (tag,body) vptr =
> do
> var <- deref vptr
> ptr <- freshNode tag
> bindVar vptr var ptr (body ptr)
> where freshNode (CharTag c) = allocChar c
> freshNode (IntTag i) = allocInt i
> freshNode (FloatTag f) = allocFloat f
> freshNode (ConstructorTag t c n) = allocVariables n >>= allocData t c
> bindVar :: NodePtr -> Node -> NodePtr -> Instruction -> Instruction
> bindVar vptr var@(VarNode cs wq) ptr next = deref ptr >>= bindVarNode ptr
> where bindVarNode _ (IndirNode ptr) = deref ptr >>= bindVarNode ptr
> bindVarNode ptr node@(VarNode cs2 wq2) =
> do
> updateState (saveBinding vptr var)
> updateNode vptr (IndirNode ptr)
> updateState (saveBinding ptr node)
> updateNode ptr (VarNode [] (wq ++ wq2))
> checkConstraints ptr (cs ++ cs2) next
> bindVarNode ptr node@(GlobalVarNode _ _) =
> if null cs && null wq then
> do
> updateState (saveBinding vptr var)
> updateNode vptr (IndirNode ptr)
> next
> else
> suspendSearch ptr node (bindVar vptr var ptr next)
> bindVarNode ptr _ =
> do
> updateState (saveBinding vptr var)
> updateNode vptr (IndirNode ptr)
> checkConstraints ptr cs (wakeQueue wq next)
> bindVar vptr _ ptr next = bindUnify vptr ptr next
> bindUnify :: NodePtr -> NodePtr -> Instruction -> Instruction
> bindUnify ptr1 ptr2 next =
> do
> updateState (pushCont (read'updateState popNode >> next))
> unifyTerms ptr1 ptr2
> checkConstraints :: NodePtr -> [Constraint] -> Instruction -> Instruction
> checkConstraints _ [] next = next
> checkConstraints ptr (DisEq ptr':cs) next =
> do
> updateState (pushNodes [ptr,ptr'])
> updateState
> (pushCont (read'updateState popNode >> checkConstraints ptr cs next))
> diseqCode
> wakeQueue :: ThreadQueue -> Instruction -> Instruction
> wakeQueue tq next = if null tq then next else wake tq next
> where wake tq next =
> do
> updateState (interruptThread next)
> updateState (wakeThreads tq)
> switchContext
> switch :: String -> [(NodeTag,NodePtr -> Instruction)]
> -> (NodePtr -> Instruction) -> Instruction
> switch v dispatchTable dflt = readState (getVar v) >>= switch
> where dispatchTable' = (IndirTag,switchIndir) : dispatchTable
> switch ptr = deref ptr >>= switchNode ptr
> switchNode ptr node =
> maybe dflt id (lookup (nodeTag node) dispatchTable') ptr
> switchIndir iptr =
> do
> IndirNode ptr <- deref iptr
> updateState (setVar v ptr)
> switch ptr
> bindArgs :: (NodePtr -> MachStateT ()) -> Instruction
> -> NodePtr -> Instruction
> bindArgs bind next ptr =
> do
> bind ptr
> next
> bindLiteral :: NodePtr -> MachStateT ()
> bindLiteral _ = return ()
> bindData :: [String] -> NodePtr -> MachStateT ()
> bindData vs ptr = deref ptr >>= bindConstrNode vs
> where bindConstrNode vs (ConstructorNode _ _ ptrs)
> | length vs == length ptrs = updateState (setVars vs ptrs)
> | otherwise = fail "Type error in switch case"
\end{verbatim}
\subsubsection{Non-deterministic Evaluation}
A \texttt{choice} statement executes its alternatives
non-deterministically. If there are other threads which can proceed
with a deterministic computation, the current thread is suspended
until these threads either finish or suspend.
\begin{verbatim}
> choice :: [Instruction] -> Instruction
> choice [] = failAndBacktrack
> choice (alt:alts)
> | null alts = alt
> | otherwise = read'updateState (yieldThread try) >>= \so ->
> if so then switchContext else try
> where try = tryChoice (alt:alts)
> tryChoice :: [Instruction] -> Instruction
> tryChoice (alt:alts) = readState curContext >>= try
> where try IOContext = fail "Cannot duplicate the world"
> try GlobalContext =
> do
> updateState (pushChoicepoint (tryNext alts))
> alt
> try _ = choiceSearch (alt:alts)
> tryNext (alt:alts) =
> do
> updateState (updChoicepoint alts)
> alt
> updChoicepoint alts
> | null alts = popChoicepoint
> | otherwise = updateChoicepoint (tryNext alts)
> failAndBacktrack :: Instruction
> failAndBacktrack = readState curContext >>= fail
> where fail IOContext = return Nothing
> fail GlobalContext =
> read'updateState backtrack >>= maybe (return Nothing) id
> fail _ = failSearch
\end{verbatim}
\subsubsection{Sequencing of Instructions}
A statement sequence $x$ \texttt{<-} \emph{st$_1$}\texttt{;}
\emph{st$_2$} binds $x$ to the result of \emph{st$_1$} and then
executes \emph{st$_2$} in the extended environment.
\begin{verbatim}
> seqStmts :: String -> Instruction -> Instruction -> Instruction
> seqStmts v first next =
> do
> updateState (pushCont bindCont)
> first
> where bindCont =
> do
> read'updateState popNode >>= updateState . setVar v
> next
\end{verbatim}
\subsection{Primitives}
\subsubsection{Application Functions}
There is a -- potentially -- unlimited number of functions
\texttt{@}$i$, which are used by the compiler for implementing
applications of a function variable to $i$ arguments.\footnote{For
historical reasons, the compiler uses \texttt{@} instead of
\texttt{@1}.}
\begin{verbatim}
> applyFunction :: Function
> applyFunction = ("@",applyCode 1,2)
> applyFunctions :: [Function]
> applyFunctions = applyFunction : [('@':show i,applyCode i,i+1) | i <- [2..]]
> applyCode :: Int -> Instruction
> applyCode n = entry ("f" : xs) $ seqStmts "_f" (enter "f") (apply "_f" xs)
> where xs = ['x':show i | i <- [1..n]]
\end{verbatim}
In order to handle partial applications of data constructors, the
compiler provides an auxiliary function for each data constructor,
which returns a new constructor node with the supplied arguments.
\begin{verbatim}
> constrFunction :: Int -> String -> Int -> Function
> constrFunction t c n = (c,constrCode t c n,n)
> constrCode :: Int -> String -> Int -> Instruction
> constrCode t c n = read'updateState (popNodes n) >>= allocData t c >>= retNode
\end{verbatim}
\subsubsection{Arithmetic Operations}\label{sec:mach-arithmetic}
All arithmetic operations are implemented as primitives.
\begin{verbatim}
> ordPrimitive,chrPrimitive :: Primitive
> ordPrimitive = ("primOrd",prim1 primOrd)
> chrPrimitive = ("primChr",prim1 primChr)
> primOrd, primChr :: NodePtr -> MachStateT NodePtr
> primOrd = withChar "ord" (allocInt . toInteger . ord)
> primChr = withInt "chr" (allocChar . chr . fromInteger)
> addIntPrimitive, subIntPrimitive, mulIntPrimitive :: Primitive
> quotIntPrimitive, remIntPrimitive :: Primitive
> divIntPrimitive, modIntPrimitive :: Primitive
> addIntPrimitive = ("primAddInt", prim2 $ primIntOp "+" (+))
> subIntPrimitive = ("primSubInt", prim2 $ primIntOp "-" (-))
> mulIntPrimitive = ("primMulInt", prim2 $ primIntOp "*" (*))
> quotIntPrimitive = ("primQuotInt", prim2 $ primIntOp "quot" quot)
> remIntPrimitive = ("primRemInt", prim2 $ primIntOp "rem" rem)
> divIntPrimitive = ("primDivInt", prim2 $ primIntOp "div" div)
> modIntPrimitive = ("primModInt", prim2 $ primIntOp "mod" mod)
> primIntOp :: String -> (Integer -> Integer -> Integer) -> NodePtr -> NodePtr
> -> MachStateT NodePtr
> primIntOp what op x y =
> withInt what (\i -> withInt what (\j -> allocInt (i `op` j)) y) x
> addFloatPrimitive, subFloatPrimitive :: Primitive
> mulFloatPrimitive, divFloatPrimitive :: Primitive
> addFloatPrimitive = ("primAddFloat", prim2 $ primFloatOp "+." (+))
> subFloatPrimitive = ("primSubFloat", prim2 $ primFloatOp "-." (-))
> mulFloatPrimitive = ("primMulFloat", prim2 $ primFloatOp "*." (*))
> divFloatPrimitive = ("primDivFloat", prim2 $ primFloatOp "/." (/))
> primFloatOp :: String -> (Double -> Double -> Double) -> NodePtr -> NodePtr
> -> MachStateT NodePtr
> primFloatOp what op x y =
> withFloat what (\e -> withFloat what (\f -> allocFloat (e `op` f)) y) x
> floatPrimitive :: Primitive
> floatPrimitive = ("primFloat", prim1 primFloat)
> primFloat :: NodePtr -> MachStateT NodePtr
> primFloat = withInt "floatFromInt" (allocFloat . fromIntegral)
> truncPrimitive, roundPrimitive :: Primitive
> truncPrimitive = ("primTrunc", prim1 $ primFromFloat "truncateFloat" truncate)
> roundPrimitive = ("primRound", prim1 $ primFromFloat "roundFloat" round)
> primFromFloat :: String -> (Double -> Integer) -> NodePtr
> -> MachStateT NodePtr
> primFromFloat what fromDouble = withFloat what (allocInt . fromDouble)
> withChar :: String -> (Char -> MachStateT a) -> NodePtr -> MachStateT a
> withChar what code ptr = deref ptr >>= withCharNode code
> where withCharNode code (CharNode c) = code c
> withCharNode _ _ = fail (what ++ ": invalid argument")
> withInt :: String -> (Integer -> MachStateT a) -> NodePtr -> MachStateT a
> withInt what code ptr = deref ptr >>= withIntNode code
> where withIntNode code (IntNode i) = code i
> withIntNode _ _ = fail (what ++ ": invalid argument")
> withFloat :: String -> (Double -> MachStateT a) -> NodePtr -> MachStateT a
> withFloat what code ptr = deref ptr >>= withFloatNode code
> where withFloatNode code (FloatNode f) = code f
> withFloatNode _ _ = fail (what ++ ": invalid argument")
\end{verbatim}
\subsubsection{Comparing Nodes}
The operator \texttt{(==)} compares two data terms for equality and
returns either \texttt{True} or \texttt{False}. In contrast to
equality constraints, this function is rigid. In addition, we support
equality checks only for literals and data terms, but not for partial
applications.
\begin{verbatim}
> equalFunction :: Function
> equalFunction = ("==",equalCode,2)
> withNode :: (Node -> Instruction) -> NodePtr -> Instruction
> withNode next ptr = deref ptr >>= next
> falseTag, trueTag :: NodeTag
> falseTag = ConstructorTag 0 "False" 0
> trueTag = ConstructorTag 1 "True" 0
> false, true :: MachStateT NodePtr
> false = read'updateState (atom falseTag)
> true = read'updateState (atom trueTag)
> bool :: Bool -> MachStateT NodePtr
> bool False = false
> bool True = true
> equalCode :: Instruction
> equalCode =
> entry ["x","y"] $ seqStmts "_x" (enter "x")
> $ switchRigid "_x" [] (withNode equalNode)
> where equalNode node =
> seqStmts "_y" (enter "y")
> (switchRigid "_y" [] (withNode (equalNodes node)))
> equalNodes :: Node -> Node -> Instruction
> equalNodes (CharNode c) (CharNode d) = bool (c == d) >>= retNode
> equalNodes (IntNode i) (IntNode j) = bool (i == j) >>= retNode
> equalNodes (FloatNode f) (FloatNode g) = bool (f == g) >>= retNode
> equalNodes (ConstructorNode t1 _ ptrs1) (ConstructorNode t2 _ ptrs2)
> | t1 == t2 = equalArgs (zip ptrs1 ptrs2)
> | otherwise = false >>= retNode
> equalNodes (ClosureNode f1 _ _ ptrs1) (ClosureNode f2 _ _ ptrs2)
> | f1 == f2 && length ptrs1 == length ptrs2 = equalArgs (zip ptrs1 ptrs2)
> | otherwise = false >>= retNode
> equalNodes _ _ = failAndBacktrack
> equalArgs :: [(NodePtr,NodePtr)] -> Instruction
> equalArgs [] = true >>= retNode
> equalArgs ((ptr1,ptr2):ptrs) =
> do
> updateState (pushNodes [ptr1,ptr2])
> unless (null ptrs)
> (updateState (pushCont (read'updateState popNode >>= equalRest ptrs)))
> equalCode
> equalRest :: [(NodePtr,NodePtr)] -> NodePtr -> Instruction
> equalRest ptrs ptr =
> do
> node <- deref ptr
> if nodeTag node == trueTag then equalArgs ptrs else retNode ptr
\end{verbatim}
The \texttt{compare} function compares two data terms and returns one
of the values \texttt{LT}, \texttt{EQ}, \texttt{GT} defined in the
\texttt{Prelude}.
\begin{verbatim}
> compareFunction :: Function
> compareFunction = ("compare",compareCode,2)
> ltTag, eqTag, gtTag :: NodeTag
> ltTag = ConstructorTag 0 "LT" 0
> eqTag = ConstructorTag 1 "EQ" 0
> gtTag = ConstructorTag 2 "GT" 0
> lt, eq, gt :: MachStateT NodePtr
> lt = read'updateState (atom ltTag)
> eq = read'updateState (atom eqTag)
> gt = read'updateState (atom gtTag)
> order :: Ordering -> MachStateT NodePtr
> order LT = lt
> order EQ = eq
> order GT = gt
> compareCode :: Instruction
> compareCode =
> entry ["x","y"] $ seqStmts "_x" (enter "x")
> $ switchRigid "_x" [] (withNode compareNode)
> where compareNode node =
> seqStmts "_y" (enter "y")
> (switchRigid "_y" [] (withNode (compareNodes node)))
> compareNodes :: Node -> Node -> Instruction
> compareNodes (CharNode c) (CharNode d) = order (compare c d) >>= retNode
> compareNodes (IntNode i) (IntNode j) = order (compare i j) >>= retNode
> compareNodes (FloatNode f) (FloatNode g) = order (compare f g) >>= retNode
> compareNodes (ConstructorNode t1 _ ptrs1) (ConstructorNode t2 _ ptrs2) =
> case compare t1 t2 of
> EQ -> compareArgs (zip ptrs1 ptrs2)
> cmp -> order cmp >>= retNode
> compareNodes _ _ = failAndBacktrack
> compareArgs :: [(NodePtr,NodePtr)] -> Instruction
> compareArgs [] = order EQ >>= retNode
> compareArgs ((ptr1,ptr2):ptrs) =
> do
> updateState (pushNodes [ptr1,ptr2])
> unless (null ptrs)
> (updateState (pushCont (read'updateState popNode >>= compareRest ptrs)))
> compareCode
> compareRest :: [(NodePtr,NodePtr)] -> NodePtr -> Instruction
> compareRest ptrs ptr =
> do
> node <- deref ptr
> if nodeTag node == eqTag then compareArgs ptrs else retNode ptr
\end{verbatim}
\subsubsection{Concurrent Conjunction}
The concurrent conjunction operator \texttt{\&} evaluates two
constraints concurrently. It tries to avoid the creation of a
new thread whenever this is possible.
\begin{verbatim}
> concConjFunction :: Function
> concConjFunction = ("&",concConjCode,2)
> concConjCode :: Instruction
> concConjCode =
> entry ["c1","c2"] $
> switch "c1"
> [(LazyTag,eval),(QueueMeTag,eval),(GlobalAppTag,eval),
> (VariableTag,variable1),(GlobalVarTag,delaySearch match1),
> (trueTag,const solve2),
> (falseTag,const failAndBacktrack)]
> (const (fail "Type error in (&)"))
> where eval ptr1 =
> switch "c2"
> [(LazyTag,const (concurrent ptr1)),
> (QueueMeTag,const (concurrent ptr1)),
> (GlobalAppTag,const (concurrent ptr1)),
> (VariableTag,variable2),(GlobalVarTag,delaySearch match2),
> (trueTag,const solve1),
> (falseTag,const failAndBacktrack)]
> (const (fail "Type error in (&)"))
> concurrent ptr1 =
> do
> qptr <- read'updateState (allocNode (LazyNode "" 1 solve [ptr1]))
> updateState (setVar "_c1" qptr)
> updateState (interruptThread (seqStmts "_" solve2 (enter "_c1")))
> updateState newThread
> updateState (setVar "_c1" qptr)
> enter "_c1"
> solve = entry ["c1"] $ solve1
> variable1 = instantiate (trueTag,const solve2)
> variable2 = instantiate (trueTag,const solve1)
> match1 =
> switch "c1"
> [(trueTag,const solve2),
> (falseTag,const failAndBacktrack)]
> (const (fail "This cannot happen"))
> match2 =
> switch "c2"
> [(trueTag,const solve1),
> (falseTag,const failAndBacktrack)]
> (const (fail "This cannot happen"))
> solve1 =
> seqStmts "_c1" (enter "c1") $
> switchFlex "_c1" [(trueTag,retNode)] (const failAndBacktrack)
> solve2 =
> seqStmts "_c2" (enter "c2") $
> switchFlex "_c2" [(trueTag,retNode)] (const failAndBacktrack)
\end{verbatim}
\subsubsection{Equality Constraints}
Unification of two arbitrary arguments is a very complex process.
Following the semantics, we have to ensure that both arguments are
evaluated to weak head normal before we actually unify the arguments.
When we have to unify two data constructors or a data constructor and
a variable, we also have to unify of the arguments of the data
constructors, which can proceed concurrently.
\begin{verbatim}
> unifyFunction :: Function
> unifyFunction = ("=:=",unifyCode,2)
> unifyCode :: Instruction
> unifyCode =
> entry ["x","y"] $ seqStmts "_x" (enter "x")
> $ seqStmts "_y" (enter "y") unifyCode'
> where unifyCode' =
> do
> ptr1 <- readState (getVar "_x")
> ptr2 <- readState (getVar "_y")
> unifyTerms ptr1 ptr2
> unifyTerms :: NodePtr -> NodePtr -> Instruction
> unifyTerms ptr1 ptr2 =
> do
> ptr1 <- derefPtr ptr1
> node1 <- deref ptr1
> ptr2 <- derefPtr ptr2
> node2 <- deref ptr2
> unifyNodes ptr1 node1 ptr2 node2
> unifyNodes :: NodePtr -> Node -> NodePtr -> Node -> Instruction
> unifyNodes ptr1 var1@(VarNode _ _) ptr2 var2@(VarNode _ _)
> | ptr1 == ptr2 = unifySuccess
> | otherwise = bindVar ptr1 var1 ptr2 unifySuccess
> unifyNodes ptr1 var1@(VarNode _ _) ptr2 var2@(GlobalVarNode _ _) =
> bindVar ptr1 var1 ptr2 unifySuccess
> unifyNodes ptr1 var1@(GlobalVarNode _ _) ptr2 var2@(VarNode _ _) =
> bindVar ptr2 var2 ptr1 unifySuccess
> unifyNodes ptr1 var@(VarNode _ _) ptr2 node =
> occursCheck ptr1 node >>= \occurs ->
> if occurs then
> failAndBacktrack
> else
> do
> (ptr',ptrs) <- freshTerm ptr2 node
> bindVar ptr1 var ptr' (unifyArgs ptrs)
> unifyNodes ptr1 node ptr2 var@(VarNode _ _) =
> unifyNodes ptr2 var ptr1 node
> unifyNodes ptr1 var1@(GlobalVarNode _ _) ptr2 var2@(GlobalVarNode _ _)
> | ptr1 == ptr2 = unifySuccess
> | otherwise = suspendSearch ptr1 var1 (unifyTerms ptr1 ptr2)
> unifyNodes ptr1 var@(GlobalVarNode _ _) ptr2 _ =
> suspendSearch ptr1 var (unifyTerms ptr1 ptr2)
> unifyNodes ptr1 _ ptr2 var@(GlobalVarNode _ _) =
> suspendSearch ptr2 var (unifyTerms ptr1 ptr2)
> unifyNodes _ (CharNode c) _ (CharNode d)
> | c == d = unifySuccess
> | otherwise = failAndBacktrack
> unifyNodes _ (IntNode i) _ (IntNode j)
> | i == j = unifySuccess
> | otherwise = failAndBacktrack
> unifyNodes _ (FloatNode f) _ (FloatNode g)
> | f == g = unifySuccess
> | otherwise = failAndBacktrack
> unifyNodes _ (ConstructorNode t1 _ ptrs1) _ (ConstructorNode t2 _ ptrs2)
> | t1 == t2 && length ptrs1 == length ptrs2 = unifyArgs (zip ptrs1 ptrs2)
> | otherwise = failAndBacktrack
> unifyNodes _ (ClosureNode f1 _ _ ptrs1) _ (ClosureNode f2 _ _ ptrs2)
> | f1 == f2 && length ptrs1 == length ptrs2 = unifyArgs (zip ptrs1 ptrs2)
> | otherwise = failAndBacktrack
> unifyNodes ptr1 (SearchContinuation _ _ _ _) ptr2 (SearchContinuation _ _ _ _)
> | ptr1 == ptr2 = unifySuccess
> | otherwise = failAndBacktrack
> unifyNodes _ _ _ _ = failAndBacktrack
> unifyArgs :: [(NodePtr,NodePtr)] -> Instruction
> unifyArgs [] = unifySuccess
> unifyArgs ((ptr1,ptr2) : ptrs)
> | null ptrs =
> do
> updateState (pushNodes [ptr1,ptr2])
> unifyCode
> | otherwise =
> do
> lazy <- allocLazy unifyFunction [ptr1,ptr2]
> updateState (setVar "c" lazy)
> updateState (interruptThread (unifyRest ptrs))
> updateState newThread
> updateState (setVar "c" lazy)
> enter "c"
> where unifyRest ptrs =
> switch "c"
> [(LazyTag,const (fail "This cannot happen")),
> (QueueMeTag,unifyRest' ptrs),
> (VariableTag,const (fail "This cannot happen"))]
> (const (unifyArgs ptrs))
> unifyRest' ptrs lazy =
> do
> updateState (pushCont unifyCont)
> unifyArgs ptrs
> unifyCont =
> do
> read'updateState popNode
> enter "c"
> unifySuccess :: Instruction
> unifySuccess = true >>= retNode
> occursCheck :: NodePtr -> Node -> MachStateT Bool
> occursCheck vptr (ConstructorNode _ _ args)
> | any (vptr ==) args = return True
> | otherwise = occursCheckArgs vptr args
> occursCheck vptr (IndirNode ptr)
> | vptr == ptr = return True
> | otherwise = deref ptr >>= occursCheck vptr
> occursCheck _ _ = return False
> occursCheckArgs :: NodePtr -> [NodePtr] -> MachStateT Bool
> occursCheckArgs _ [] = return False
> occursCheckArgs vptr (ptr:ptrs) =
> deref ptr >>= occursCheck vptr >>= \occurs ->
> if occurs then return True else occursCheckArgs vptr ptrs
> freshTerm :: NodePtr -> Node -> MachStateT (NodePtr,[(NodePtr,NodePtr)])
> freshTerm ptr (ConstructorNode t c ptrs)
> | null ptrs = return (ptr,[])
> | otherwise =
> do
> vars <- allocVariables (length ptrs)
> ptr' <- allocData t c vars
> return (ptr',zip vars ptrs)
> freshTerm ptr (ClosureNode f n code ptrs)
> | null ptrs = return (ptr,[])
> | length ptrs < n =
> do
> vars <- allocVariables (length ptrs)
> ptr' <- allocClosure (f,code,n) vars
> return (ptr',zip vars ptrs)
> | otherwise = fail (f ++ " applied to too many arguments")
> freshTerm ptr _ = return (ptr,[])
\end{verbatim}
\subsubsection{Disequality Constraints}
Disequality constraints are implemented by the primitive function
\texttt{=/=}. This function evaluates both arguments to head normal
form, first. If one argument is a (local) variable node, the other
argument is evaluated to normal form and added as a constraint to the
variable. Otherwise the tags of both arguments are compared and if
they match the disequality is distributed over the arguments of the
data constructors.
\ToDo{Do not add redundant constraints to a variable, e.g., if a
variable $x$ is already constrained to be different from $y$ it is not
necessary to add the constraint $\not= x$ to $y$.}
\ToDo{Avoid the distribution of argument disequalities when this is
possible. For instance, it is not necessary to split the computation
for the disequality \texttt{(0:xs) =/= [0]}.}
\begin{verbatim}
> diseqFunction :: Function
> diseqFunction = ("=/=",diseqCode,2)
> diseqCode :: Instruction
> diseqCode =
> entry ["x","y"] $ seqStmts "_x" (enter "x")
> $ seqStmts "_y" (enter "y") diseqCode'
> where diseqCode' =
> do
> ptr1 <- readState (getVar "_x")
> ptr2 <- readState (getVar "_y")
> diseqTerms ptr1 ptr2
> diseqTerms :: NodePtr -> NodePtr -> Instruction
> diseqTerms ptr1 ptr2 =
> do
> ptr1 <- derefPtr ptr1
> node <- deref ptr1
> ptr2 <- derefPtr ptr2
> node' <- deref ptr2
> diseqNodes ptr1 node ptr2 node'
> diseqNodes :: NodePtr -> Node -> NodePtr -> Node -> Instruction
> diseqNodes ptr1 var1@(VarNode cs1 wq1) ptr2 var2@(VarNode cs2 wq2)
> | ptr1 == ptr2 = failAndBacktrack
> | otherwise =
> do
> updateState (saveBinding ptr1 var1)
> updateNode ptr1 (VarNode (DisEq ptr2 : cs1) wq1)
> diseqSuccess
> diseqNodes ptr1 var1@(VarNode cs1 wq1) ptr2 var2@(GlobalVarNode _ _) =
> do
> updateState (saveBinding ptr1 var1)
> updateNode ptr1 (VarNode (DisEq ptr2 : cs1) wq1)
> diseqSuccess
> diseqNodes ptr1 var1@(GlobalVarNode _ _) ptr2 var2@(VarNode cs2 wq2) =
> do
> updateState (saveBinding ptr2 var2)
> updateNode ptr2 (VarNode (DisEq ptr1 : cs2) wq2)
> diseqSuccess
> diseqNodes ptr1 var@(VarNode cs wq) ptr2 node =
> occursCheck ptr1 node >>= \occurs ->
> if occurs then
> diseqSuccess
> else
> do
> updateState (saveBinding ptr1 var)