2019-02-25 18:37:24 +03:00
|
|
|
(require 'mal/types)
|
|
|
|
(require 'mal/reader)
|
|
|
|
(require 'mal/printer)
|
2016-02-28 23:22:03 +03:00
|
|
|
|
|
|
|
(defvar repl-env (make-hash-table :test 'eq))
|
|
|
|
(puthash '+ (lambda (a b) (mal-number (+ (mal-value a) (mal-value b)))) repl-env)
|
|
|
|
(puthash '- (lambda (a b) (mal-number (- (mal-value a) (mal-value b)))) repl-env)
|
|
|
|
(puthash '* (lambda (a b) (mal-number (* (mal-value a) (mal-value b)))) repl-env)
|
|
|
|
(puthash '/ (lambda (a b) (mal-number (/ (mal-value a) (mal-value b)))) repl-env)
|
|
|
|
|
|
|
|
(defun READ (input)
|
|
|
|
(read-str input))
|
|
|
|
|
|
|
|
(defun EVAL (ast env)
|
2022-01-10 02:15:40 +03:00
|
|
|
;; (println "EVAL: %s\n" (PRINT ast))
|
|
|
|
(cl-case (mal-type ast)
|
|
|
|
(list
|
|
|
|
(let ((a (mal-value ast)))
|
|
|
|
(if a
|
|
|
|
(let* ((fn (EVAL (car a) env))
|
|
|
|
(args (mapcar (lambda (x) (EVAL x env)) (cdr a))))
|
2016-02-28 23:22:03 +03:00
|
|
|
(apply fn args))
|
2022-01-10 02:15:40 +03:00
|
|
|
ast)))
|
2020-07-21 19:01:48 +03:00
|
|
|
(symbol
|
2022-01-10 02:15:40 +03:00
|
|
|
(let ((definition (gethash (mal-value ast) env)))
|
2016-02-28 23:22:03 +03:00
|
|
|
(or definition (error "Definition not found"))))
|
2020-07-21 19:01:48 +03:00
|
|
|
(vector
|
2022-01-10 02:15:40 +03:00
|
|
|
(mal-vector (vconcat (mapcar (lambda (item) (EVAL item env))
|
|
|
|
(mal-value ast)))))
|
2020-07-21 19:01:48 +03:00
|
|
|
(map
|
2022-01-10 02:15:40 +03:00
|
|
|
(let ((map (copy-hash-table (mal-value ast))))
|
2020-07-21 19:01:48 +03:00
|
|
|
(maphash (lambda (key val)
|
|
|
|
(puthash key (EVAL val env) map))
|
2016-02-28 23:22:03 +03:00
|
|
|
map)
|
|
|
|
(mal-map map)))
|
|
|
|
(t
|
|
|
|
;; return as is
|
2022-01-10 02:15:40 +03:00
|
|
|
ast)))
|
2016-02-28 23:22:03 +03:00
|
|
|
|
|
|
|
(defun PRINT (input)
|
|
|
|
(pr-str input t))
|
|
|
|
|
|
|
|
(defun rep (input)
|
|
|
|
(PRINT (EVAL (READ input) repl-env)))
|
|
|
|
|
|
|
|
(defun readln (prompt)
|
|
|
|
;; C-d throws an error
|
|
|
|
(ignore-errors (read-from-minibuffer prompt)))
|
|
|
|
|
|
|
|
(defun println (format-string &rest args)
|
|
|
|
(if (not args)
|
|
|
|
(princ format-string)
|
|
|
|
(princ (apply 'format format-string args)))
|
|
|
|
(terpri))
|
|
|
|
|
|
|
|
(defun main ()
|
|
|
|
(let (eof)
|
|
|
|
(while (not eof)
|
|
|
|
(let ((input (readln "user> ")))
|
|
|
|
(if input
|
|
|
|
(condition-case err
|
|
|
|
(println (rep input))
|
|
|
|
(end-of-token-stream
|
|
|
|
;; empty input, carry on
|
|
|
|
)
|
|
|
|
(unterminated-sequence
|
2020-07-21 19:01:48 +03:00
|
|
|
(princ (format "Expected '%c', got EOF\n"
|
|
|
|
(cl-case (cadr err)
|
|
|
|
(string ?\")
|
|
|
|
(list ?\))
|
|
|
|
(vector ?\])
|
|
|
|
(map ?})))))
|
2016-02-28 23:22:03 +03:00
|
|
|
(error ; catch-all
|
|
|
|
(println (error-message-string err))
|
|
|
|
(backtrace)))
|
|
|
|
(setq eof t)
|
|
|
|
;; print final newline
|
|
|
|
(terpri))))))
|
|
|
|
|
|
|
|
(main)
|