Merge pull request #358 from bjh21/bjh21-extra-tests
[jackhill/mal.git] / guile / step8_macros.scm
CommitLineData
e658ffd2
NG
1;; Copyright (C) 2015
2;; "Mu Lei" known as "NalaGinrut" <NalaGinrut@gmail.com>
3;; This file is free software: you can redistribute it and/or modify
4;; it under the terms of the GNU General Public License as published by
5;; the Free Software Foundation, either version 3 of the License, or
6;; (at your option) any later version.
7
8;; This file is distributed in the hope that it will be useful,
9;; but WITHOUT ANY WARRANTY; without even the implied warranty of
10;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11;; GNU General Public License for more details.
12
13;; You should have received a copy of the GNU General Public License
14;; along with this program. If not, see <http://www.gnu.org/licenses/>.
15
16(import (readline) (reader) (printer) (ice-9 match) (srfi srfi-43)
17 (srfi srfi-1) (ice-9 receive) (env) (core) (types))
18
19(define *toplevel*
20 (receive (b e) (unzip2 core.ns)
dcd15199 21 (make-Env #:binds b #:exprs (map make-func e))))
e658ffd2 22
dd7a4f55
JM
23(define (READ str)
24 (read_str str))
e658ffd2
NG
25
26(define (eval_ast ast env)
27 (define (_eval x) (EVAL x env))
28 (match ast
29 ((? _nil? obj) obj)
30 ((? symbol? sym) (env-has sym env))
31 ((? list? lst) (map _eval lst))
32 ((? vector? vec) (vector-map (lambda (i x) (_eval x)) vec))
33 ((? hash-table? ht)
dd7a4f55
JM
34 ;; NOTE: we must allocate a new hashmap here to avoid any side-effects, or
35 ;; there'll be strange bugs!!!
36 (list->hash-map (hash-fold (lambda (k v p) (cons k (cons (_eval v) p))) '() ht)))
e658ffd2
NG
37 (else ast)))
38
e658ffd2
NG
39(define (eval_seq ast env)
40 (cond
41 ((null? ast) nil)
42 ((null? (cdr ast)) (EVAL (car ast) env))
43 (else
44 (EVAL (car ast) env)
45 (eval_seq (cdr ast) env))))
46
47(define (is_macro_call ast env)
48 (and (list? ast)
81eabb99 49 (> (length ast) 0)
85657c96 50 (and=> (env-check (car ast) env) is-macro)))
e658ffd2
NG
51
52(define (_macroexpand ast env)
53 (cond
54 ((is_macro_call ast env)
55 => (lambda (c)
e658ffd2
NG
56 ;; NOTE: Macros are normal-order, so we shouldn't eval args here.
57 ;; Or it's applicable-order.
58 (_macroexpand (callable-apply c (cdr ast)) env)))
59 (else ast)))
60
61(define (EVAL ast env)
62 (define (%unzip2 kvs)
63 (let lp((next kvs) (k '()) (v '()))
64 (cond
65 ;; NOTE: reverse is very important here!
66 ((null? next) (values (reverse k) (reverse v)))
dd7a4f55
JM
67 ((null? (cdr next))
68 (throw 'mal-error (format #f "let*: Invalid binding form '~a'" kvs)))
e658ffd2
NG
69 (else (lp (cddr next) (cons (car next) k) (cons (cadr next) v))))))
70 (define (_quasiquote obj)
71 (match obj
72 ((('unquote unq) rest ...) `(cons ,unq ,(_quasiquote rest)))
73 (('unquote unq) unq)
74 ((('splice-unquote unqsp) rest ...) `(concat ,unqsp ,(_quasiquote rest)))
75 ((head rest ...) (list 'cons (_quasiquote head) (_quasiquote rest)))
76 (else `(quote ,obj))))
77 ;; NOTE: I wish I can use (while #t ...) for that, but this is not Lispy, which means
78 ;; it'll bring some trouble in control flow. We have to use continuations to return
79 ;; and use non-standard `break' feature. In a word, not elegant at all.
80 ;; The named let loop is natural for Scheme, but it looks a bit cheating. But NO!
81 ;; Such kind of loop is actually `while loop' in Scheme, I don't take advantage of
82 ;; TCO in Scheme to implement TCO, but it's the same principle with normal loop.
83 ;; If you're Lispy enough, there's no recursive at all while you saw named let loop.
84 (let tco-loop((ast ast) (env env)) ; expand as possible
e658ffd2
NG
85 (let ((ast (_macroexpand ast env)))
86 (match ast
87 ((? non-list?) (eval_ast ast env))
81eabb99 88 (() ast)
e658ffd2
NG
89 (('defmacro! k v)
90 (let ((c (EVAL v env)))
91 (callable-is_macro-set! c #t)
92 ((env 'set) k c)))
93 (('macroexpand obj) (_macroexpand obj env))
94 (('quote obj) obj)
95 (('quasiquote obj) (EVAL (_quasiquote (->list obj)) env))
96 (('def! k v) ((env 'set) k (EVAL v env)))
97 (('let* kvs body)
98 (let* ((new-env (make-Env #:outer env))
99 (setter (lambda (k v) ((new-env 'set) k (EVAL v new-env)))))
100 (receive (keys vals) (%unzip2 (->list kvs))
101 (for-each setter keys vals))
102 (tco-loop body new-env)))
103 (('do rest ...)
104 (cond
dd7a4f55
JM
105 ((null? rest)
106 (throw 'mal-error (format #f "do: Invalid form! '~a'" rest)))
e658ffd2
NG
107 ((= 1 (length rest)) (tco-loop (car rest) env))
108 (else
109 (let ((mexpr (take rest (1- (length rest))))
110 (tail-call (car (take-right rest 1))))
111 (eval_seq mexpr env)
112 (tco-loop tail-call env)))))
113 (('if cnd thn els ...)
114 (cond
115 ((and (not (null? els)) (not (null? (cdr els))))
116 ;; Invalid `if' form
dd7a4f55
JM
117 (throw 'mal-error
118 (format #f "if: failed to match any pattern in form '~a'" ast)))
e658ffd2
NG
119 ((cond-true? (EVAL cnd env)) (tco-loop thn env))
120 (else (if (null? els) nil (tco-loop (car els) env)))))
121 (('fn* params body ...) ; function definition
dd7a4f55 122 (make-anonymous-func
e658ffd2
NG
123 (lambda args
124 (let ((nenv (make-Env #:outer env #:binds (->list params) #:exprs args)))
125 (cond
dd7a4f55
JM
126 ((null? body)
127 (throw 'mal-error (format #f "fn*: bad lambda in form '~a'" ast)))
e658ffd2
NG
128 ((= 1 (length body)) (tco-loop (car body) nenv))
129 (else
130 (let ((mexpr (take body (1- (length body))))
131 (tail-call (car (take-right body 1))))
132 (eval_seq mexpr nenv)
133 (tco-loop tail-call nenv))))))))
dd7a4f55
JM
134 (else
135 (let ((el (map (lambda (x) (EVAL x env)) ast)))
136 (callable-apply (car el) (cdr el))))))))
e658ffd2
NG
137
138(define (EVAL-string str)
139 (EVAL (read_str str) *toplevel*))
140
141(define (PRINT exp)
142 (and (not (eof-object? exp))
e658ffd2
NG
143 (format #t "~a~%" (pr_str exp #t))))
144
145(define (LOOP continue?)
146 (and continue? (REPL)))
147
148(define (REPL)
149 (LOOP
dd7a4f55
JM
150 (let ((line (_readline "user> ")))
151 (cond
152 ((eof-object? line) #f)
153 ((string=? line "") #t)
154 (else
155 (catch 'mal-error
156 (lambda () (PRINT (EVAL (READ line) *toplevel*)))
157 (lambda (k . e)
158 (format #t "Error: ~a~%" (pr_str (car e) #t)))))))))
e658ffd2
NG
159
160;; initialization
161((*toplevel* 'set) 'eval (make-func (lambda (ast) (EVAL ast *toplevel*))))
162((*toplevel* 'set) '*ARGV* '())
17fc310d 163(EVAL-string "(def! not (fn* (x) (if x false true)))")
e658ffd2
NG
164(EVAL-string "(def! load-file (fn* (f) (eval (read-string (str \"(do \" (slurp f) \")\")))))")
165(EVAL-string "(defmacro! cond (fn* (& xs) (if (> (count xs) 0) (list 'if (first xs) (if (> (count xs) 1) (nth xs 1) (throw \"odd number of forms to cond\")) (cons 'cond (rest (rest xs)))))))")
166(EVAL-string "(defmacro! or (fn* (& xs) (if (empty? xs) nil (if (= 1 (count xs)) (first xs) `(let* (or_FIXME ~(first xs)) (if or_FIXME or_FIXME (or ~@(rest xs))))))))")
1ad90e2b
NG
167
168(let ((args (cdr (command-line))))
2f60d14c
NG
169 (cond
170 ((> (length args) 0)
4b3eaa74
NG
171 ((*toplevel* 'set) '*ARGV* (cdr args))
172 (EVAL-string (string-append "(load-file \"" (car args) "\")")))
173 (else (REPL))))