-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathenvironment.py
42 lines (31 loc) · 1.16 KB
/
environment.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import runtimeError
class Environment():
def __init__(self, enclosing=None):
self.values={}
self.enclosing=enclosing
def define(self, name, value):
self.values[name]=value
def get(self, name):
if name.lexeme in self.values:
return self.values[name.lexeme]
if self.enclosing is not None:
return self.enclosing.get(name)
raise RuntimeError(name, "Undefined variable '"+name.lexeme+"'.")
def getAt(self, distance, name):
# print(self.ancestor(distance).values)
return self.ancestor(distance).values.get(name)
def ancestor(self, distance):
env=self
for i in range(distance):
env=env.enclosing
return env
def assign(self, name, value):
if name.lexeme in self.values:
self.values[name.lexeme]=value
return
if self.enclosing is not None:
self.enclosing.assign(name, value)
return
raise RuntimeError(name, "Undefined variable '"+name.lexeme+"'.")
def assignAt(self, distance, name, value):
self.ancestor(distance).values[name]=value