2 (import (scheme write))
14 (define (eval-ast ast env)
15 (let ((type (and (mal-object? ast) (mal-type ast)))
16 (value (and (mal-object? ast) (mal-value ast))))
18 ((symbol) (env-get env value))
19 ((list) (mal-list (map (lambda (item) (EVAL item env)) value)))
20 ((vector) (mal-vector (vector-map (lambda (item) (EVAL item env)) value)))
21 ((map) (mal-map (alist-map (lambda (key value) (cons key (EVAL value env))) value)))
24 (define (EVAL ast env)
25 (let ((type (and (mal-object? ast) (mal-type ast))))
26 (if (not (eq? type 'list))
28 (let ((items (mal-value ast)))
31 (case (mal-value (car items))
33 (let ((symbol (mal-value (cadr items)))
34 (value (EVAL (list-ref items 2) env)))
35 (env-set env symbol value)
38 (let ((env* (make-env env))
39 (binds (->list (mal-value (cadr items))))
40 (form (list-ref items 2)))
41 (let loop ((binds binds))
43 (let ((key (mal-value (car binds))))
44 (when (null? (cdr binds))
45 (error "unbalanced list"))
46 (let ((value (EVAL (cadr binds) env*)))
47 (env-set env* key value)
48 (loop (cddr binds))))))
51 (let ((forms (cdr items)))
54 ;; the evaluation order of map is unspecified
55 (let loop ((forms forms))
56 (let ((form (car forms))
64 (let* ((condition (EVAL (cadr items) env))
65 (type (and (mal-object? condition)
66 (mal-type condition))))
67 (if (memq type '(false nil))
68 (if (< (length items) 4)
70 (EVAL (list-ref items 3) env))
71 (EVAL (list-ref items 2) env))))
73 (let* ((binds (->list (mal-value (cadr items))))
74 (binds (map mal-value binds))
75 (body (list-ref items 2)))
77 (let ((env* (make-env env binds args)))
80 (let* ((items (mal-value (eval-ast ast env)))
83 (apply op ops)))))))))
88 (define repl-env (make-env #f))
89 (for-each (lambda (kv) (env-set repl-env (car kv) (cdr kv))) ns)
92 (PRINT (EVAL (READ input) repl-env)))
94 (rep "(def! not (fn* (a) (if a false true)))")
98 (let ((input (readline "user> ")))
101 (ex ((error-object? ex)
102 (when (not (memv 'empty-input (error-object-irritants ex)))
104 (display (error-object-message ex))
106 ((and (pair? ex) (eq? (car ex) 'user-error))
108 (display (pr-str (cdr ex) #t))
110 (display (rep input))