Skip to content

Commit

Permalink
Centralize macro cache
Browse files Browse the repository at this point in the history
  • Loading branch information
nickdrozd committed Jan 17, 2024
1 parent d945a85 commit e258689
Showing 1 changed file with 18 additions and 10 deletions.
28 changes: 18 additions & 10 deletions tm/macro.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from abc import abstractmethod
from typing import TYPE_CHECKING
from collections import defaultdict

from tm.parse import tcompile

Expand All @@ -13,6 +14,17 @@

########################################

COLOR_TO_TAPE_CACHE: dict[
int,
dict[Color, tuple[Color, ...]],
] = defaultdict(dict)

TAPE_TO_COLOR_CACHE: dict[
int,
dict[tuple[Color, ...], Color],
] = defaultdict(dict)


class MacroProg:
program: str | GetInstr
comp: GetInstr
Expand All @@ -29,9 +41,6 @@ class MacroProg:

cells: int

color_to_tape_cache: dict[Color, tuple[Color, ...]]
tape_to_color_cache: dict[tuple[Color, ...], Color]

def __init__(self, program: str | GetInstr):
self.program = program

Expand All @@ -56,9 +65,6 @@ def __init__(self, program: str | GetInstr):

self.instrs = {}

self.color_to_tape_cache = {}
self.tape_to_color_cache = {}

def __getitem__(self, slot: Slot) -> Instr | None:
try:
instr = self.instrs[slot]
Expand Down Expand Up @@ -139,7 +145,7 @@ def run_simulator(self, config: Config) -> Config | None:
return state, (cells <= pos, tape)

def tape_to_color(self, tape: Tape) -> Color:
if (cached := self.tape_to_color_cache.get(
if (cached := TAPE_TO_COLOR_CACHE[cells := self.cells].get(
tuple_tape := tuple(tape))) is not None:
return cached

Expand All @@ -148,16 +154,18 @@ def tape_to_color(self, tape: Tape) -> Color:
for place, value in enumerate(reversed(tape))
)

self.tape_to_color_cache[tuple_tape] = color
self.color_to_tape_cache[color] = tuple_tape
TAPE_TO_COLOR_CACHE[cells][tuple_tape] = color
COLOR_TO_TAPE_CACHE[cells][color] = tuple_tape

return color

def color_to_tape(self, color: Color) -> Tape:
if color == 0:
return [0] * self.cells

assert (prev := self.color_to_tape_cache.get(color)) is not None
assert (
prev := COLOR_TO_TAPE_CACHE[self.cells].get(color)
) is not None

return list(prev)

Expand Down

0 comments on commit e258689

Please sign in to comment.