-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack-v3.scm
136 lines (116 loc) · 2.69 KB
/
stack-v3.scm
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
;;; stack-alloc static chain, that's envirenment.
(use-modules (ice-9 format))
(use-modules (ice-9 pretty-print))
(load "utils.scm")
(load "stack.scm")
(define *debug* #t)
;;; env utilities
;;; ((vars . vals) env-link)
(define extend
(lambda (env vars)
(cons vars env)))
(define comp-lookup
(lambda (var e fn)
(let nextrib ((e e) (rib 0))
(let nextelt ((vars (car e))
(elt 0))
(cond
((null? vars) (nextrib (cdr e) (+ rib 1)))
((eq? var (car vars)) (fn rib elt))
(else (nextelt (cdr vars) (+ elt 1))))))))
(define env '())
;;; compile, name comp to avoid name conflict.
(define comp
(lambda (x e next)
(cond
((symbol? x)
(comp-lookup x e
(lambda (n m)
(list 'refer n m next))))
((pair? x)
(record-case x
(quote (obj)
(list 'const obj next))
(lambda (vars body)
(list 'close
(comp body
(extend e vars)
(list 'return (1+ (length vars))))
next))
(if (test then else)
(let ((thenpart (comp then e next))
(elsepart (comp else e next)))
(comp test e (list 'test thenpart elsepart))))
(call/cc (x)
(list 'frame
next
(list 'conti
(list 'arg
(comp x e '(apply))))))
(t
(let loop ((args (cdr x))
(c (comp (car x) e '(apply))))
(if (null? args)
`(frame ,next ,c)
(loop (cdr args)
(comp (car args)
e
`(arg ,c))))))))
(else
(list 'const x next)))))
(define (decode inst)
(let ((op (car inst)))
(format #t "$ ~s~%" op)))
;;; rib is in the stack
(define nip 100)
(define VM
(lambda (a x e s)
(if *debug*
(decode x))
(if (= nip 0)
"exceeds"
(set! nip (1- nip)))
(record-case x
(halt () a)
(refer (n m x)
(VM (index (find-link n e) m) x e s))
(const (obj x)
(VM obj x e s))
(close (body x)
(VM (closure body e) x e s))
(test (then else)
(VM a (if a then else) e s))
(conti (x)
(VM (continuation s) x e s))
(nuate (s x)
(VM a x e (restore-stack s)))
(frame (ret x)
(VM a x e (push ret (push e s))))
(arg (x)
(VM a x e (push a s)))
(apply ()
(record (body e) a
(VM a body s (push e s))))
(return (n)
(let ((s (- s n)))
(VM a (index s 0) (index s 1) (- s 2))))
)))
(define closure
(lambda (body e)
(list body e)))
(define continuation
(lambda (s)
(closure
(list 'refer 0 0 (list 'nuate (save-stack s) '(return 0)))
'())))
(define go
(lambda (x)
(let ((code (comp x '() '(halt))))
(if *debug*
(pretty-print code))
(VM '() code env 0))))
(define find-link
(lambda (n e)
(cond
((= n 0) e)
(else (find-link (1- n) (index e -1))))))