|
| 1 | +"""Utilities for exploring nondeterminism in the recursive descent segment.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import os |
| 6 | +import random |
| 7 | +import sys |
| 8 | +from collections import deque |
| 9 | +from typing import TYPE_CHECKING |
| 10 | +from typing import Deque |
| 11 | +from typing import Iterable |
| 12 | +from typing import List |
| 13 | +from typing import Optional |
| 14 | +from typing import TextIO |
| 15 | +from typing import Tuple |
| 16 | + |
| 17 | +if TYPE_CHECKING: |
| 18 | + from jsonpath_rfc9535.environment import JSONLikeData |
| 19 | + |
| 20 | + |
| 21 | +HORIZONTAL_SEP = "\N{BOX DRAWINGS LIGHT HORIZONTAL}" * 2 |
| 22 | +VERTICAL_SEP = "\N{BOX DRAWINGS LIGHT VERTICAL}" |
| 23 | +BRANCH = "\N{BOX DRAWINGS LIGHT VERTICAL AND RIGHT}" + HORIZONTAL_SEP + " " |
| 24 | +TERMINAL_BRANCH = "\N{BOX DRAWINGS LIGHT UP AND RIGHT}" + HORIZONTAL_SEP + " " |
| 25 | +INDENT = VERTICAL_SEP + " " * 3 |
| 26 | +TERMINAL_INDENT = " " * 4 |
| 27 | + |
| 28 | +COLOR_CODES = [ |
| 29 | + ("\033[92m", "\033[0m"), |
| 30 | + ("\033[93m", "\033[0m"), |
| 31 | + ("\033[94m", "\033[0m"), |
| 32 | + ("\033[95m", "\033[0m"), |
| 33 | + ("\033[96m", "\033[0m"), |
| 34 | + ("\033[91m", "\033[0m"), |
| 35 | +] |
| 36 | + |
| 37 | + |
| 38 | +class AuxNode: |
| 39 | + def __init__( |
| 40 | + self, |
| 41 | + depth: int, |
| 42 | + value: object, |
| 43 | + children: Optional[List[AuxNode]] = None, |
| 44 | + ) -> None: |
| 45 | + self.value = value |
| 46 | + self.children = children or [] |
| 47 | + self.depth = depth |
| 48 | + |
| 49 | + def __str__(self) -> str: |
| 50 | + c_start, c_stop = COLOR_CODES[self.depth % len(COLOR_CODES)] |
| 51 | + return f"{c_start}{self.value}{c_stop}" |
| 52 | + |
| 53 | + @staticmethod |
| 54 | + def from_(data: JSONLikeData) -> AuxNode: |
| 55 | + def _visit(node: AuxNode, depth: int = 0) -> None: |
| 56 | + if isinstance(node.value, dict): |
| 57 | + for val in node.value.values(): |
| 58 | + _node = AuxNode(depth + 1, val) |
| 59 | + _visit(_node, depth + 1) |
| 60 | + node.children.append(_node) |
| 61 | + |
| 62 | + elif isinstance(node.value, list): |
| 63 | + for val in node.value: |
| 64 | + _node = AuxNode(depth + 1, val) |
| 65 | + _visit(_node, depth + 1) |
| 66 | + node.children.append(_node) |
| 67 | + |
| 68 | + root = AuxNode(0, data) |
| 69 | + _visit(root) |
| 70 | + return root |
| 71 | + |
| 72 | + |
| 73 | +def pptree( |
| 74 | + node: AuxNode, |
| 75 | + indent: str = "", |
| 76 | + buf: TextIO = sys.stdout, |
| 77 | +) -> None: |
| 78 | + """Pretty print the tree rooted at `node`.""" |
| 79 | + # Pre-order tree traversal |
| 80 | + buf.write(str(node) + os.linesep) |
| 81 | + |
| 82 | + if node.children: |
| 83 | + # Recursively call pptree for all but the last child of `node`. |
| 84 | + for child in node.children[:-1]: |
| 85 | + buf.write(indent + BRANCH) |
| 86 | + pptree(child, indent=indent + INDENT, buf=buf) |
| 87 | + |
| 88 | + # Terminal branch case for last, possibly only, child of `node`. |
| 89 | + buf.write(indent + TERMINAL_BRANCH) |
| 90 | + pptree(node.children[-1], indent=indent + TERMINAL_INDENT, buf=buf) |
| 91 | + |
| 92 | + # Base case. No children. |
| 93 | + |
| 94 | + |
| 95 | +def pre_order_visit(node: AuxNode) -> Iterable[AuxNode]: |
| 96 | + yield node |
| 97 | + |
| 98 | + for child in node.children: |
| 99 | + yield from pre_order_visit(child) |
| 100 | + |
| 101 | + |
| 102 | +def breadth_first_visit(node: AuxNode) -> Iterable[AuxNode]: |
| 103 | + queue: Deque[AuxNode] = deque([node]) |
| 104 | + |
| 105 | + while queue: |
| 106 | + _node = queue.popleft() |
| 107 | + yield _node |
| 108 | + queue.extend(_node.children) |
| 109 | + |
| 110 | + |
| 111 | +def nondeterministic_visit(root: AuxNode) -> Iterable[AuxNode]: |
| 112 | + queue: Deque[AuxNode] = deque(root.children) |
| 113 | + yield root |
| 114 | + |
| 115 | + while queue: |
| 116 | + _node = queue.popleft() |
| 117 | + yield _node |
| 118 | + for child in _node.children: |
| 119 | + # Queue the child node or visit it now? |
| 120 | + if random.choice([True, False]): # noqa: S311 |
| 121 | + queue.append(child) |
| 122 | + else: |
| 123 | + yield child |
| 124 | + queue.extend(child.children) |
| 125 | + |
| 126 | + |
| 127 | +def get_perms(root: AuxNode) -> List[Tuple[AuxNode, ...]]: |
| 128 | + perms = {tuple(nondeterministic_visit(root)) for _ in range(1000)} |
| 129 | + perms.add(tuple(pre_order_visit(root))) |
| 130 | + return sorted(perms, key=lambda t: str(t)) |
| 131 | + |
| 132 | + |
| 133 | +def pp_json_path_data(data: JSONLikeData) -> None: |
| 134 | + aux_tree = AuxNode.from_(data) |
| 135 | + pptree(aux_tree) |
| 136 | + |
| 137 | + print("\nPre order\n") |
| 138 | + print(", ".join(str(n) for n in pre_order_visit(aux_tree))) |
| 139 | + |
| 140 | + print("\nLevel order\n") |
| 141 | + print(", ".join(str(n) for n in breadth_first_visit(aux_tree))) |
| 142 | + |
| 143 | + print("\nNondeterministic order\n") |
| 144 | + for perm in get_perms(aux_tree): |
| 145 | + print(", ".join(str(node) for node in perm)) |
| 146 | + |
| 147 | + |
| 148 | +if __name__ == "__main__": |
| 149 | + # basic, descendant segment, name shorthand |
| 150 | + data = {"o": [{"a": "b"}, {"a": "c"}]} |
| 151 | + pp_json_path_data(data) |
0 commit comments