43 lines
1.8 KiB
Python
43 lines
1.8 KiB
Python
from typing import Dict, Optional, List, Any, Tuple
|
|
from MaMa import MaMa
|
|
|
|
class MaMaMa(MaMa):
|
|
def __init__(self, prog, stack=None) -> None:
|
|
self.macros: Dict[str, Dict[str, Any]] = {}
|
|
self.initial_macros: Dict[str, Dict[str, Any]] = {}
|
|
self._macro_trace: Dict[int, List[str]] = {}
|
|
super().__init__(prog, stack)
|
|
|
|
def add_macro(self, name: str, prog: List[str] | Dict[int, str], args: List[str] = None) -> None:
|
|
if isinstance(prog, list):
|
|
prog = {i: instr for i, instr in enumerate(prog)}
|
|
self.macros[name] = {"prog": prog, "args": args}
|
|
self.initial_macros[name] = dict(self.macros[name])
|
|
|
|
def run(self, max_steps: int = 1000):
|
|
# automatically flatten macros before execution
|
|
self._expand_macros_into_prog()
|
|
return super().run(max_steps)
|
|
|
|
# --- flatten macros recursively before execution ---
|
|
def _expand_macros_into_prog(self) -> None:
|
|
def expand(prog: Dict[int, str], stack: List[str]) -> List[Tuple[str, List[str]]]:
|
|
out: List[Tuple[str, List[str]]] = []
|
|
for _, call in sorted(prog.items()):
|
|
name, args = self.decode(call)
|
|
if name in self.macros:
|
|
out.extend(expand(self.macros[name]["prog"], stack + [name]))
|
|
else:
|
|
out.append((call, list(stack)))
|
|
return out
|
|
|
|
expanded = expand(self.prog, [])
|
|
self.prog = {i: call for i, (call, _) in enumerate(expanded)}
|
|
self._macro_trace = {i: macros for i, (_, macros) in enumerate(expanded)}
|
|
|
|
def structure(self) -> Dict[int, Dict[str, Any]]:
|
|
return {
|
|
i: {"call": call, "macros": self._macro_trace.get(i, []), "p_prog": self.p_prog}
|
|
for i, call in sorted(self.prog.items())
|
|
}
|