-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMemory.py
More file actions
61 lines (42 loc) · 1.87 KB
/
Memory.py
File metadata and controls
61 lines (42 loc) · 1.87 KB
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
from errors import UndeclaredVariableError
class Memory:
def __init__(self, parent, level): # memory name
self.parent = parent
self.level = level
self.variables = dict()
def has_key(self, name): # variable name
return name in self.variables
def get(self, name): # gets from memory current value of variable <name>
if name in self.variables:
return self.variables[name]
return self.parent.get(name)
def put(self, name, value): # puts into memory current value of variable <name>
self.variables[name] = value
if self.parent != None:
self.parent.variables[name] = value
scope = self.search(name)
if scope:
scope.variables[name] = value
else:
self.variables[name] = value
#searches for earliest instance of a variable
def search(self, name):
if self is None:
return None
if name in self.variables:
return self
return self.parent.search(name)
def get_parent(self):
return self.parent
class MemoryStack:
def __init__(self): # initialize memory stack with memory <memory>
self.global_memory = Memory(None, 0)
self.current_memory = self.global_memory
def get(self, name): # gets from memory stack current value of variable <name>
return self.current_memory.get(name)
def put(self, name, value): # sets variable <name> to value <value>
self.current_memory.put(name, value)
def push(self): # pushes memory <memory> onto the stack
self.current_memory = Memory(self.current_memory, self.current_memory.level+1)
def pop(self): # pops the top memory from the stack
self.current_memory = self.current_memory.get_parent()