-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathenvironment.py
36 lines (28 loc) · 1.13 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
from lox_token import Token
from runtime_error import LoxRuntimeError
class Environment:
""" Tracks variables """
def __init__(self, enclosing: 'Environment' or None = None):
# signature uses forward refrences to indicate that the enclosing arg is an Environment class type
self.values = {}
self.enclosing = enclosing
def define(self, key, value):
# note that since we overwrite without checking existence, the variable can be reassigned
# via the "var" keyword
self.values[key] = value
def assign(self, name: Token, value):
key = name.lexeme
if key in self.values:
self.values[key] = value
return
if self.enclosing is not None:
self.enclosing.assign(name, value)
return
raise LoxRuntimeError(name, f'Undefined variable: {key}')
def get(self, name: Token):
key = name.lexeme
if key in self.values:
return self.values[key]
if self.enclosing is not None:
return self.enclosing.get(name)
raise LoxRuntimeError(name, f'Undefined variable: {key}')