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

41 lines
1.4 KiB
Python
Raw Normal View History

2015-06-10 07:07:03 +03:00
from mal_types import MalType, MalSym, MalList, throw_str
2015-06-04 07:16:37 +03:00
# Environment
class Env():
def __init__(self, outer=None, binds=None, exprs=None):
self.data = {}
self.outer = outer or None
if binds:
2015-06-09 05:58:37 +03:00
assert isinstance(binds, MalList) and isinstance(exprs, MalList)
2015-06-04 07:16:37 +03:00
for i in range(len(binds)):
2015-06-09 05:58:37 +03:00
bind = binds[i]
if not isinstance(bind, MalSym):
throw_str("env bind value is not a symbol")
2015-06-09 05:58:37 +03:00
if bind.value == u"&":
bind = binds[i+1]
if not isinstance(bind, MalSym):
throw_str("env bind value is not a symbol")
2015-06-09 05:58:37 +03:00
self.data[bind.value] = exprs.slice(i)
2015-06-04 07:16:37 +03:00
break
else:
2015-06-09 05:58:37 +03:00
self.data[bind.value] = exprs[i]
2015-06-04 07:16:37 +03:00
def find(self, key):
assert isinstance(key, MalSym)
if key.value in self.data: return self
elif self.outer: return self.outer.find(key)
else: return None
def set(self, key, value):
assert isinstance(key, MalSym)
assert isinstance(value, MalType)
self.data[key.value] = value
return value
def get(self, key):
assert isinstance(key, MalSym)
env = self.find(key)
2015-06-10 07:07:03 +03:00
if not env: throw_str("'" + str(key.value) + "' not found")
2015-06-04 07:16:37 +03:00
return env.data[key.value]