# RoboScript #3 - Implement the RS2 Specification

## Disclaimer

The story presented in this Kata Series is purely fictional; any resemblance to actual programming languages, products, organisations or people should be treated as purely coincidental.

## About this Kata Series

This Kata Series is based on a fictional story about a computer scientist and engineer who owns a firm that sells a toy robot called MyRobot which can interpret its own (esoteric) programming language called RoboScript.  Naturally, this Kata Series deals with the software side of things (I'm afraid Codewars cannot test your ability to build a physical robot!).

## Story

Last time, you implemented the RS1 specification which allowed your customers to write more concise scripts for their robots by allowing them to simplify consecutive repeated commands by postfixing a non-negative integer onto the selected command.  For example, if your customers wanted to make their robot move 20 steps to the right, instead of typing `FFFFFFFFFFFFFFFFFFFF`, they could simply type `F20` which made their scripts more concise.  However, you later realised that this simplification wasn't enough.  What if a set of commands/moves were to be repeated?  The code would still appear cumbersome.  Take the program that makes the robot move in a snake-like manner, for example.  The shortened code for it was `F4LF4RF4RF4LF4LF4RF4RF4LF4LF4RF4RF4` which still contained a lot of repeated commands.

## Task

Your task is to allow your customers to further shorten their scripts and make them even more concise by implementing the newest specification of RoboScript (at the time of writing) that is RS2.  RS2 syntax is a superset of RS1 syntax which means that all valid RS1 code from the previous Kata of this Series should still work with your RS2 interpreter.  The only main addition in RS2 is that the customer should be able to group certain sets of commands using round brackets.  For example, the last example used in the previous Kata in this Series:


LF5RF3RF3RF7
 

... can be expressed in RS2 as:


LF5(RF3)(RF3R)F7


Or ... 


(L(F5(RF3))(((R(F3R)F7))))


Simply put, your interpreter should be able to deal with nested brackets of any level.

And of course, brackets are useless if you cannot use them to repeat a sequence of movements!  Similar to how individual commands can be postfixed by a non-negative integer to specify how many times to repeat that command, a sequence of commands grouped by round brackets `()` should also be repeated `n` times provided a non-negative integer is postfixed onto the brackets, like such:


(SEQUENCE_OF_COMMANDS)n


... is equivalent to ... 


SEQUENCE_OF_COMMANDS...SEQUENCE_OF_COMMANDS (repeatedly executed "n" times)


For example, this RS1 program:


F4LF4RF4RF4LF4LF4RF4RF4LF4LF4RF4RF4


... can be rewritten in RS2 as:


F4L(F4RF4RF4LF4L)2F4RF4RF4


Or:


F4L((F4R)2(F4L)2)2(F4R)2F4


All 4 example tests have been included for you.  Good luck :D

## Kata in this Series

1. [RoboScript #1 - Implement Syntax Highlighting](https://www.codewars.com/kata/roboscript-number-1-implement-syntax-highlighting)
2. [RoboScript #2 - Implement the RS1 Specification](https://www.codewars.com/kata/roboscript-number-2-implement-the-rs1-specification)
3. **RoboScript #3 - Implement the RS2 Specification**
4. [RoboScript #4 - RS3 Patterns to the Rescue](https://www.codewars.com/kata/594b898169c1d644f900002e)
5. [RoboScript #5 - The Final Obstacle (Implement RSU)](https://www.codewars.com/kata/5a12755832b8b956a9000133)

```python

USER_FILENAME = "<user_code>"
import sys, json, builtins
import math, heapq, bisect, itertools, functools, collections, statistics, fractions, decimal, operator, array, random, re, string, os, pathlib
try:
    import resource as _res
except Exception:
    _res = None
from collections import Counter, defaultdict, deque, OrderedDict
from functools import lru_cache, reduce
from itertools import accumulate, permutations, combinations, product
from math import gcd, ceil, floor, sqrt
from decimal import Decimal
try:
    from typing import *
except Exception:
    pass
try:
    sys.setrecursionlimit(1_000_000)
except Exception:
    pass
try:
    import site as _site
    try:
        _sys_sites = _site.getsitepackages() if hasattr(_site, "getsitepackages") else []
        for _p in _sys_sites:
            if _p and _p not in sys.path:
                sys.path.append(_p)
    except Exception:
        pass
    try:
        _usp = _site.getusersitepackages()
        if isinstance(_usp, str):
            _usp = [_usp]
        for _p in _usp:
            if _p and _p not in sys.path:
                sys.path.append(_p)
    except Exception:
        pass
except Exception:
    pass

def _disabled_input(*args, **kwargs):
    raise RuntimeError("input() is disabled in callable mode")
builtins.input = _disabled_input

ns = {"__name__": "__judge__"}  # prevent if __name__ == "__main__" blocks
for _k, _v in list(globals().items()):
    if not _k.startswith("_"):
        ns[_k] = _v
_CODE = "from typing import Tuple, Optional, Union, Any, List, Dict, Callable, Iterator\nfrom enum import Enum, auto\nimport re\n\nOptFunc = Optional[Callable[[], Any]]\n\ninstructions_pattern = re.compile(r'F+\\d*|L+\\d*|R+\\d*')\n\n\nclass BufferedIterator:\n    _iter: Iterator[str]\n    _stack: List[str]\n\n    def __init__(self, it: Iterator[str]):\n        self._iter = it\n        self._stack = []\n\n    def __iter__(self):\n        return self\n\n    def __next__(self):\n        if self._stack:\n            return self._stack.pop()\n        else:\n            return next(self._iter)\n\n    def push(self, s):\n        self._stack.append(s)\n\n\nclass StringBuf:\n    _text: str\n\n    def __init__(self, s: Optional[str] = None):\n        self._text = s or ''\n\n    def __str__(self):\n        return self._text\n\n    def __repr__(self):\n        return f'StringBuf({self._text!r})'\n\n    def append(self, s: str):\n        self._text += s\n\n    def prepend(self, s: str):\n        self._text = s + self._text\n\n    def __getitem__(self, idx):\n        return self._text[idx]\n\n    def __setitem__(self, idx, value):\n        if isinstance(idx, int):\n            self._text = self._text[:idx] + value + self._text[(idx + len(value)):]\n\n\nclass Rotation(Enum):\n    No = auto()\n    Left = auto()\n    Right = auto()\n\n    def switch(self, right: OptFunc = None, left: OptFunc = None, none: OptFunc = None) -> Any:\n        if self is self.Right:\n            if right is not None:\n                return right()\n        elif self is self.Left:\n            if left is not None:\n                return left()\n        elif self is self.No:\n            if none is not None:\n                return none()\n\n        return None\n\n\nclass Direction(Enum):\n    Up = 0\n    Right = 1\n    Down = 2\n    Left = 3\n\n    @staticmethod\n    def from_num(count: int) -> 'Direction':\n        return Direction((4 - (-count % 4)) % 4 if count < 0 else count % 4)\n\n    def to_num(self) -> int:\n        return self.value\n\n    def switch(self, up: OptFunc = None, right: OptFunc = None, down: OptFunc = None, left: OptFunc = None) -> Any:\n        if self is self.Up:\n            if up is not None:\n                return up()\n        elif self is self.Right:\n            if right is not None:\n                return right()\n        elif self is self.Down:\n            if down is not None:\n                return down()\n        elif self is self.Left:\n            if left is not None:\n                return left()\n\n        return None\n\n    def next(self, pos: Tuple[int, int], count: int) -> Tuple[int, int]:\n        return self.switch(\n            up=lambda: (pos[0], pos[1] - count),\n            right=lambda: (pos[0] + count, pos[1]),\n            down=lambda: (pos[0], pos[1] + count),\n            left=lambda: (pos[0] - count, pos[1]),\n        )\n\n    def change(self, rot: Rotation, count: int) -> 'Direction':\n        return rot.switch(\n            left=lambda: Direction.from_num(self.to_num() - count),\n            right=lambda: Direction.from_num(self.to_num() + count),\n            none=lambda: self,\n        )\n\n\nclass TheGridForTron:\n    _grid: List[StringBuf]\n    _size: int\n    _org: Tuple[int, int]\n    _pos: Tuple[int, int]\n    _dir: Direction\n\n    def __init__(self):\n        self._grid = [StringBuf('*')]\n        self._size = 1\n        self._org = (0, 0)\n        self._pos = (0, 0)\n        self._dir = Direction.Right\n\n    def _grow(self):\n        # Grow to left\n        diff = self._org[0] - self._pos[0]\n        if diff > 0:\n            self._org = (self._pos[0], self._org[1])\n            self._size += diff\n\n            s = ' ' * diff\n\n            for line in self._grid:\n                line.prepend(s)\n\n            return\n\n        # Grow to up\n        diff = self._org[1] - self._pos[1]\n        if diff > 0:\n            self._org = (self._org[0], self._pos[1])\n\n            s = ' ' * self._size\n            for _ in range(diff):\n                self._grid.insert(0, StringBuf(s))\n\n            return\n\n        # Grow to right\n        diff = self._pos[0] - (self._org[0] + self._size) + 1\n        if diff > 0:\n            s = ' ' * diff\n\n            self._size += diff\n            for line in self._grid:\n                line.append(s)\n\n            return\n\n        # Grow to down\n        diff = self._pos[1] - (self._org[1] + len(self._grid)) + 1\n        if diff > 0:\n            s = ' ' * self._size\n            for _ in range(diff):\n                self._grid.append(StringBuf(s))\n\n    def _trace_path(self, old: Tuple[int, int]):\n        def up():\n            pos = self._pos[0] - self._org[0]\n            org = self._org[1]\n\n            for line in self._grid[(self._pos[1] - org):(old[1] - org)]:\n                line[pos] = '*'\n\n        def right():\n            self._grid[self._pos[1] - self._org[1]][old[0] + 1 - self._org[0]] = '*' * (self._pos[0] - old[0])\n\n        def down():\n            pos = self._pos[0] - self._org[0]\n            org = self._org[1]\n\n            for line in self._grid[(old[1] + 1 - org):(self._pos[1] + 1 - org)]:\n                line[pos] = '*'\n\n        def left():\n            self._grid[self._pos[1] - self._org[1]][self._pos[0] - self._org[0]] = '*' * (old[0] - self._pos[0])\n\n        self._dir.switch(\n            up=up,\n            right=right,\n            down=down,\n            left=left,\n        )\n\n    def do_move(self, rot: Rotation, count: int):\n        if rot is Rotation.No:\n            old = self._pos\n\n            self._pos = self._dir.next(self._pos, count)\n            self._grow()\n            self._trace_path(old)\n        else:\n            self._dir = self._dir.change(rot, count)\n\n    def serialize(self) -> str:\n        return '\\r\\n'.join(map(str, self._grid))\n\n\nclass Executor:\n    _grid: TheGridForTron\n    _actions: Dict[str, Callable[[int], Any]]\n\n    def __init__(self, grid: TheGridForTron):\n        self._grid = grid\n        self._actions = {\n            'F': lambda cnt: self._grid.do_move(Rotation.No, cnt),\n            'L': lambda cnt: self._grid.do_move(Rotation.Left, cnt),\n            'R': lambda cnt: self._grid.do_move(Rotation.Right, cnt),\n        }\n\n    def do_actions(self, code: str):\n        for m in instructions_pattern.finditer(code):\n            action, count = parse_instruction(m.group())\n\n            self._actions.get(action, lambda _: None)(count)\n\n\ndef expand_code(code: BufferedIterator) -> str:\n    res: str = ''\n    sub_str: str = ''\n    in_group: bool = False\n    count: Union[None, int] = None\n\n    for ch in code:\n        if in_group:\n            try:\n                count = ((count or 0) * 10) + int(ch)\n            except ValueError:\n                code.push(ch)\n                if count is not None:\n                    sub_str *= count\n                    count = None\n\n                res += sub_str\n                sub_str = ''\n                in_group = False\n        else:\n            if ch == ')':\n                break\n\n            if ch == '(':\n                sub_str = expand_code(code)\n                in_group = True\n                continue\n\n            res += ch\n\n    if sub_str:\n        if count is not None:\n            sub_str *= count\n\n        res += sub_str\n\n    return res\n\n\ndef parse_instruction(code: str) -> Tuple[str, int]:\n    c = code[0]\n\n    count = code.lstrip(c)\n    n = len(code) - len(count)\n\n    if count:\n        n += int(count) - 1\n\n    return c, n\n\n\ndef execute(code: str) -> str:\n    grid = TheGridForTron()\n\n    Executor(grid).do_actions(expand_code(BufferedIterator(iter(code))))\n\n    return grid.serialize()\n"
_co = compile(_CODE, USER_FILENAME, "exec")
exec(_co, ns, ns)

_target = None
_fn_name = 'execute'
if _fn_name:
    if "Solution" in ns:
        try:
            _obj = ns["Solution"]()
            if hasattr(_obj, _fn_name):
                _target = getattr(_obj, _fn_name)
        except Exception:
            _target = None
    if _target is None and _fn_name in ns and callable(ns[_fn_name]):
        _target = ns[_fn_name]
# Fallback: if there's exactly one user-defined function, use it
if _target is None:
    _cands = [v for k, v in ns.items() if callable(v) and getattr(v, "__module__", "") in ("__judge__", "__main__")]
    _user_funcs = [c for c in _cands if getattr(c, "__name__", "").startswith("_") is False]
    if len(_user_funcs) == 1:
        _target = _user_funcs[0]
if _target is None:
    raise RuntimeError(f"Could not resolve callable '{_fn_name}'")

_raw = sys.stdin.read().strip()
if _raw:
    _parsed = json.loads(_raw)
    if isinstance(_parsed, dict):
        _kwargs = _parsed.get("kwargs", {})
        _args = _parsed.get("args", [])
    else:
        _args, _kwargs = _parsed, {}
else:
    _args, _kwargs = [], {}
if not isinstance(_args, (list, tuple)):
    _args = [_args]
_res = _target(*_args, **_kwargs)
try:
    sys.stdout.write(repr(_res) + "\n")
except Exception:
    pass

```

Measured memory_bytes: 18881