1
1
mirror of https://github.com/kanaka/mal.git synced 2024-09-20 01:57:09 +03:00
mal/impls/guile/env.scm

65 lines
2.2 KiB
Scheme
Raw Normal View History

2015-03-27 14:19:58 +03:00
;; Copyright (C) 2015
;; "Mu Lei" known as "NalaGinrut" <NalaGinrut@gmail.com>
;; This file is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;; This file is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
(library (env)
2015-04-02 21:39:02 +03:00
(export make-Env env-has env-check)
2015-03-27 14:19:58 +03:00
(import (guile) (types)))
2015-04-02 21:39:02 +03:00
(define (env-check sym env)
(env-has sym env (lambda _ #f)))
(define (sym-err-throw sym)
(throw 'mal-error (format #f "'~a' not found" sym)))
(define* (env-has sym env #:optional (err sym-err-throw))
2015-04-01 21:50:52 +03:00
(let ((v ((env 'get) sym)))
2015-04-01 22:05:05 +03:00
(if (equal? v '*mal-null*)
2015-04-02 21:39:02 +03:00
(err sym)
2015-04-01 22:05:05 +03:00
v)))
2015-04-01 21:50:52 +03:00
2015-03-30 09:33:31 +03:00
(define* (make-Env #:key (outer nil) (binds '()) (exprs '()))
2015-03-27 14:19:58 +03:00
(define _env (make-hash-table))
(define (_set k v) (hash-set! _env k v))
2015-03-27 14:19:58 +03:00
(define (_get k)
2015-04-01 21:50:52 +03:00
(let ((v (hash-ref _env k '*mal-null*)))
(if (equal? v '*mal-null*)
2015-04-02 21:39:02 +03:00
(if (_nil? outer)
'*mal-null*
((outer 'get) k))
2015-04-01 21:50:52 +03:00
v)))
2015-03-27 14:19:58 +03:00
(define (_find k) (_get k))
2015-04-01 21:50:52 +03:00
(define (_show)
(hash-for-each (lambda (k v) (format #t "~a : ~a~%" k v)) _env)
2015-04-02 21:39:02 +03:00
(display "outer:\n")
2015-04-01 21:50:52 +03:00
(and (not (_nil? outer)) ((outer 'show))))
2015-03-30 21:31:40 +03:00
(let lp((b binds) (e exprs))
(cond
((null? b) #t)
((eq? (car b) '&) (hash-set! _env (cadr b) e)) ; handle varglist
(else ; normal binding
(when (not (symbol? (car b)))
(throw 'mal-error (format #f "Invalid binding key! '~a'" (car b))))
2015-04-02 21:39:02 +03:00
(when (null? e)
(throw 'mal-error "Invalid pattern for this macro"))
2015-03-30 21:31:40 +03:00
(hash-set! _env (car b) (car e))
(lp (cdr b) (cdr e)))))
2015-03-27 14:19:58 +03:00
(lambda (cmd)
(case cmd
((set) _set)
((find) _find)
((get) _get)
2015-04-01 21:50:52 +03:00
((show) _show)
(else (throw 'mal-error (format #f "BUG: Invalid cmd '~a'" cmd))))))