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
|
#lang eopl
; 3.9 INTERPRETER
; - the interpreter consists of several components
; - SCANNER - converts characters to tokens
; - PARSER - converts tokens to abstract syntax trees
; - ENVIRONMENT - maps identifiers to values
; - EVALUATOR - converts abstract syntax trees to values/results
; - this interpreter supports:
; - (3.1) basic functionality
; - whitespace & comments (skipped)
; - integers & built-in defined constants
; - 3 binary primitive operations - add, sub, mult
; - 2 unary primitive operations - incr, decr
; - (3.3) conditionals - if-then-else
; - (3.4) local bindings - let
; - (3.5) procedures - proc, app-exp
; - (3.6) recursion - letrec
; - (3.7) variable assignment - set
; - (3.9) statements - assign, print, compound, if, while, block
;
; THINGS DO DO (save as 3.9a)
; ------------------------------------------------------------
; scanner specification
(define scanner-spec
'(
(whitespace (whitespace) skip)
(comment ("%" (arbno (not #\newline))) skip)
(identifier (letter (arbno (or letter digit "?"))) make-symbol)
(number (digit (arbno digit)) make-number) ))
; ------------------------------------------------------------
; grammar specification
(define grammar
'(
; (3.1) program
(program (statement) a-program)
; (3.9) statements
(statement (identifier "=" expression)
assign-statement)
(statement ("print" "(" expression ")")
print-statement)
(statement ("{" (separated-list statement ";") "}")
compound-statement)
(statement ("if" expression statement statement)
if-statement)
(statement ("while" expression "do" statement)
while-statement)
(statement ("var" (separated-list identifier ",") ";" statement)
block-statement)
(statement ("do" "{" statement "}" "while" expression) do-while-statement)
; (3.1) expressions
(expression (number) lit-exp)
(expression (identifier) var-exp)
(expression (primitive "(" (separated-list expression ",") ")")
primapp-exp)
; (3.3) conditional evaluation
(expression ("if" expression "then" expression "else" expression)
if-exp)
; (3.4) local binding
(expression ("let" (arbno identifier "=" expression) "in" expression)
let-exp)
; (3.5) procedure definition & application
(expression ("proc" "(" (separated-list identifier ",") ")" expression)
proc-exp)
(expression ("(" expression (arbno expression) ")")
app-exp)
; (3.6) recursion
(expression ("letrec"
(arbno identifier "(" (separated-list identifier ",") ")"
"=" expression)
"in" expression)
letrec-exp)
; (3.7) variable assignment
(expression ("set" identifier "=" expression)
varassign-exp)
; (3.7 HW) sequential expressions
(expression ("begin" expression (arbno ";" expression) "end")
begin-exp)
; (3.1) primitives
(primitive ("+") add-prim)
(primitive ("-") subtract-prim)
(primitive ("*") mult-prim)
(primitive ("add1") incr-prim)
(primitive ("sub1") decr-prim)
; (3.3) primitives
(primitive ("equal?") equal-prim)
(primitive ("zero?") zero-prim)
(primitive ("greater?") greater-prim)
(primitive ("less?") less-prim)
))
; ------------------------------------------------------------
; define datatypes before defining interpreter
(sllgen:make-define-datatypes scanner-spec grammar)
(define dump-datatypes
(lambda () (sllgen:list-define-datatypes scanner-spec grammar)))
; ------------------------------------------------------------
; booleans
(define truth 1)
(define falsity 0)
(define true-value? (lambda (x) (not (zero? x))))
; ------------------------------------------------------------
; environments
(define init-env
(lambda () (extend-env '(stdout) '(*uninitialized*) (empty-env)) ))
(define-datatype environment environment?
(empty-env-record)
(extended-env-record
(syms (list-of symbol?))
(vec vector?) ; can use this for anything
(env environment?) ))
(define empty-env (lambda () (empty-env-record)))
(define extend-env
(lambda (syms vals env) (extended-env-record syms (list->vector vals) env)))
(define extend-env-recursively
(lambda (proc-names idss bodies old-env)
(let ((len (length proc-names)))
(let ((vec (make-vector len)))
(let ((env (extended-env-record proc-names vec old-env)))
(for-each
(lambda (pos ids body)
(vector-set! vec pos (closure ids body env)))
(iota len)
idss
bodies)
env)))))
(define apply-env-ref
(lambda (env sym)
(cases environment env
(empty-env-record ()
(eopl:error 'apply-env "no association for symbol ~s" sym))
(extended-env-record (syms vals env)
(let ((position (env-find-position sym syms)))
(if (number? position) (a-ref position vals) (apply-env-ref env sym)))))))
(define apply-env
(lambda (env sym) (deref (apply-env-ref env sym))))
(define env-find-position
(lambda (sym los) (list-find-position sym los)))
(define list-find-position
(lambda (sym los) (list-index (lambda (sym1) (eqv? sym1 sym)) los)))
(define list-index
(lambda (pred ls)
(cond
((null? ls) #f)
((pred (car ls)) 0)
(else (let ((list-index-r (list-index pred (cdr ls))))
(if (number? list-index-r) (+ list-index-r 1) #f))))))
(define iota
(lambda ( n ) (do ((n n (- n 1)) (x '() (cons (- n 1) x))) ((zero? n) x))))
; ------------------------------------------------------------
; evaluator
; evaluator for root of abstract syntax tree
(define execute-program
(lambda (pgm)
(cases program pgm
(a-program (statement)
(execute-statement statement (init-env)) ))))
; (3.9) statement evaluator
(define execute-statement
(lambda (stmt env)
(cases statement stmt
(assign-statement (id exp)
(setref!
(apply-env-ref env id)
(eval-expression exp env) ))
(print-statement (exp)
(write (eval-expression exp env)) (newline) )
(compound-statement (statements)
(for-each
(lambda (statement) (execute-statement statement env))
statements) )
(if-statement (exp true-statement false-statement)
(if (true-value? (eval-expression exp env))
(execute-statement true-statement env)
(execute-statement false-statement env) ))
; alternate "named" LET syntax
(while-statement (exp statement)
(let loop ()
(if (true-value? (eval-expression exp env))
(begin
(execute-statement statement env)
(loop) ))))
(do-while-statement (stmt exp)
(execute-statement stmt env)
(let loop ()
(if (true-value? (eval-expression exp env))
(begin
(execute-statement stmt env)
(loop)) )))
(block-statement (ids statement)
(execute-statement statement
(extend-env ids (map (lambda (id) 0) ids) env) ))
)))
; expression evaluator
(define eval-expression
(lambda (exp env)
(cases expression exp
(lit-exp (datum) datum)
(var-exp (id) (apply-env env id))
(primapp-exp (prim rands)
(let ((args (eval-rands rands env)))
(apply-primitive prim args)))
; (3.3) conditional evaluation
(if-exp (test-exp true-exp false-exp)
(if (true-value? (eval-expression test-exp env))
(eval-expression true-exp env)
(eval-expression false-exp env) ))
; (3.4) local binding
(let-exp (ids rands body)
(let ((args (eval-rands rands env)))
(eval-expression body (extend-env ids args env))))
; (3.5) procedure definition
(proc-exp (ids body) (closure ids body env))
; (3.5) procedure application
(app-exp (rator rands)
(let ((proc (eval-expression rator env))
(args (eval-rands rands env)) )
(if (procval? proc)
(apply-procval proc args)
(eopl:error 'eval-expression
"attempt to apply non-procedure ~s"
proc))))
; (3.6) recursion
(letrec-exp (proc-names idss bodies letrec-body)
(eval-expression letrec-body
(extend-env-recursively proc-names idss bodies env)))
; (3.7) variable assignment
(varassign-exp (id rhs-exp)
(begin (setref!
(apply-env-ref env id)
(eval-expression rhs-exp env))
1))
; (3.7) sequential expressions
(begin-exp (exp1 exps)
(letrec
((loop (lambda (acc exps)
(if (null? exps) acc
(loop (eval-expression (car exps) env)
(cdr exps))))))
(loop (eval-expression exp1 env) exps)))
)))
; (3.4) evaluate operands
(define eval-rands
(lambda (rands env) (map (lambda (x) (eval-rand x env)) rands)))
(define eval-rand
(lambda (rand env) (eval-expression rand env)))
; (3.1) apply primitive operations
(define apply-primitive
(lambda (prim args)
(define (check arity)
(if (not (= arity (length args)))
(eopl:error 'apply-primitive
"wrong number of arguments to primitive ~s"
prim)))
(cases primitive prim
(add-prim () (check 2) (+ (car args) (cadr args)))
(subtract-prim () (check 2) (- (car args) (cadr args)))
(mult-prim () (check 2) (* (car args) (cadr args)))
(incr-prim () (check 1) (+ (car args) 1))
(decr-prim () (check 1) (- (car args) 1))
(equal-prim () (check 2) (if (= (car args) (cadr args)) truth falsity))
(zero-prim () (check 1) (if (zero? (car args)) truth falsity))
(greater-prim () (check 2) (if (> (car args) (cadr args)) truth falsity))
(less-prim () (check 2) (if (< (car args) (cadr args)) truth falsity))
)))
; ------------------------------------------------------------
; procedures (3.5)
(define-datatype procval procval?
(closure
(ids (list-of symbol?)) ; formal parameters
(body expression?) ; procedure body
(env environment?))) ; closure (calling environment)
(define apply-procval
(lambda (proc args)
(cases procval proc
(closure (ids body env)
(if (= (length ids) (length args))
(eval-expression body (extend-env ids args env))
(eopl:error 'apply-procval
"wrong number of arguments to procedure ~s"
ids))))))
; ------------------------------------------------------------
; references - for variable assignment (3.7)
(define-datatype reference reference?
(a-ref
(position integer?)
(vec vector?) ))
(define primitive-deref
(lambda (ref)
(cases reference ref
(a-ref (pos vec)
(vector-ref vec pos) ))))
(define primitive-setref!
(lambda (ref value)
(cases reference ref
(a-ref (pos vec)
(vector-set! vec pos value)))))
(define deref (lambda (ref) (primitive-deref ref)))
(define setref! (lambda (ref value) (primitive-setref! ref value)))
; ------------------------------------------------------------
; interpreter
; scanner only, and parser only
(define scan
(sllgen:make-string-scanner scanner-spec grammar))
(define scan&parse
(sllgen:make-string-parser scanner-spec grammar))
(define read-dump
(sllgen:make-rep-loop "--> " (lambda (tree) tree)
(sllgen:make-stream-parser scanner-spec grammar)))
(define scan&parse&eval
(lambda (s) (execute-program (scan&parse s))) )
(define read-eval-print
(sllgen:make-rep-loop "--> " execute-program
(sllgen:make-stream-parser scanner-spec grammar)))
; ------------------------------------------------------------
; tests
(define test-3.1a "add1(2)")
; ignores extra parameters
(define test-3.1b "add1(2,3)")
(define test-3.1c "+(3,4,5)")
; more tests
(define test-3.1d "+(add1(2),-(6,4))")
(define test-3.1e "*(2,+(3,sub1(4)))")
(define test-3.3a "if -(3,+(1,2)) then 2 else 3")
(define test-3.4a "let x = 5 y = 6 in +(x,y)")
(define test3.5a "print(let f=proc(y,z) +(y,-(z,5)) in (f 2 28))")
(define test3.5b "print((proc (x) +(x,2) 4))")
(define test3.5c "print(let x=5 in let f=proc(y,z) +(y,-(z,x)) x=28 in (f 2 x))")
(define test3.6a "print(letrec fact(x)=if zero?(x) then 1 else *(x,(fact sub1(x)))
in (fact 6))")
(define test3.6b "print(letrec even(x)=if zero?(x) then 1 else (odd sub1(x))
odd(x)=if zero?(x) then 0 else (even sub1(x))
in (odd 13))")
(define test3.9a "var x,y; {x=3; y=4; print(+(x,y))}")
(define test3.9b "var x,y,z; {x=3; y=4; z=0;
while x do {z=+(z,y); x=sub1(x)}; print(z)}")
|