| 4 | |
| 5 | |
| 6 | class Frame: |
| 7 | __slots__ = ("locals", "previous") |
| 8 | |
| 9 | def __init__(self): |
| 10 | self.locals = {} |
| 11 | self.previous = None # type: Frame |
| 12 | |
| 13 | def _lookup(self, key: str) -> Any: |
| 14 | if type(key) != str: |
| 15 | raise TypeError("Key index must be a string") |
| 16 | |
| 17 | if key in self.locals: |
| 18 | return (self, self.locals[key]) |
| 19 | elif self.previous is not None: |
| 20 | return self.previous._lookup(key) |
| 21 | else: |
| 22 | raise KeyError("No such variable in stack frames") |
| 23 | |
| 24 | def __getitem__(self, key: str): |
| 25 | if type(key) != str: |
| 26 | raise TypeError("Key index must be a string") |
| 27 | |
| 28 | return self._lookup(key)[1] |
| 29 | |
| 30 | def __setitem__(self, key: str, value): |
| 31 | if type(key) != str: |
| 32 | raise TypeError("Key index must be a string") |
| 33 | |
| 34 | if key in self.locals: |
| 35 | self.locals[key] = value |
| 36 | |
| 37 | try: |
| 38 | loc, _ = self.previous[key] |
| 39 | loc[key] = value |
| 40 | except (TypeError, KeyError): |
| 41 | self.locals[key] = value |
| 42 | |
| 43 | def copy(self) -> Frame: |
| 44 | l = self.locals.copy() |
| 45 | frame_copy = Frame() |
| 46 | frame_copy.locals = l.copy() |
| 47 | return frame_copy |
| 48 | |
| 49 | @property |
| 50 | def variables(self) -> List[str]: |
| 51 | l = list(self.locals.keys()) |
| 52 | |
| 53 | if self.previous: |
| 54 | l.extend(self.previous.variables) |
| 55 | return l |
| 56 | |
| 57 | |
| 58 | class Stack: |